Forcing the garbage collector to run

  • Thread starter Thread starter IcedCrow
  • Start date Start date
I

IcedCrow

I know I read everywhere that you "can't" force the
garbage collector to run, and that you really have no
control when it runs.

However as a programmer I know that there is always a way
around something.

So I ask you, how do you force the garbage collector to
run and clean up?
 
GC.Collect will manually force it to fire..whether or not you actually want
to do that is another question.

You can also pass in a Param for the generation so you can just collect
specific generations.

HTH,

Bill
 
IcedCrow,
I know I read everywhere that you "can't" force the
garbage collector to run, and that you really have no
control when it runs.
I've never read that you can't force the GC to run, only that you should
normally not force it to run.

As William stated, you can use GC.Collect to force the garbage collector to
run.

Generally you should follow GC.Collect with a call to
GC.WaitForPendingFinalizers, then you should follow this with another call
to GC.Collect, followed by a second call to GC.WaitForPendingFinalizers.

As GC.Collect by itself will put objects into the finalization list,
GC.WaitForPendingFinalizers will remove these object from the list.
GC.Collect will then clean up these finalizable objects. Which may have
created more finalizable objects...

However it is highly advisable not to call GC.Collect as it takes care of
itself and you will potentially hurt performance rather then help
performance. The GC is self tuning, and if you call GC.Collect, the GC may
get 'out of sync'.

The following two articles covers when you should & should not call
GC.Collect.

http://msdn.microsoft.com/msdnmag/issues/1100/gci/
http://msdn.microsoft.com/msdnmag/issues/1200/GCI2/

Hope this helps
Jay
 
Back
Top