force garbage collection

can we force garbage collection to be run


Answer this question

force garbage collection

  • hackmonkey

    In order for garbage collection to occur, no application threads can be running. Forcing a garbage collection means you're forcing your threads to suspend. If your threads don't really support being suspended for an indeterminate amount of time then you may run into problems by forcing a garbage collection. e.g. if your thread locks a region of a file temporarily while processing, that lock may remain much longer than you expect.

    Another problem is WaitForPendingFinalizers blocks your program for an indeterminate amount of time, so you don't want to call it on your main/UI thread.



  • une

    System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if
    situations arises.



  • rperreta

    A single garbage collection does not guarantees you that all unused memory is reclaimed since the finalizers are not garbage-collected

    You must do the following to be sure that all available memory is claimed back:

    //Force garbage collection.
    GC.Collect();

    // Wait for all finalizers to complete before continuing.
    // Without this call to GC.WaitForPendingFinalizers,
    // the worker loop below might execute at the same time
    // as the finalizers.
    // With this call, the worker loop executes only after
    // all finalizers have been called.
    GC.WaitForPendingFinalizers();

    //Forces another garbage collection.
    GC.Collect();



  • imanish11111

    Calling it is really expenssive for the CPU, so I think there is rarely a situation where you need to call it if your code is well in releasing used resources. Anyways this option is still available for us to use.

    Best regards,



  • force garbage collection