Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use GC.Collect() in .NET? [duplicate]

Possible Duplicate:
When is it acceptable to call GC.Collect?

From what I know the CLR does all this garbage collection for you, but is there a reason to manually call GC.Collect()?

Is it for cases when you close a file, dispose of an image resource or an unmanaged resource, that you should call GC.Collect() to quickly clean up the unused memory immediately?

like image 698
Joan Venge Avatar asked Mar 21 '11 20:03

Joan Venge


2 Answers

Is it for cases when you close a file, dispose of an image resource or an unmanaged resource, that you should call GC.Collect() to quickly clean up the unused memory immediately?

No, not really. This is typically handled via IDisposable.

There are very few reasons to call GC.Dispose() directly, and doing so often causes a lot of harm, since it interferes with the internal heuristics of the GC in .NET. There are, however, rare occurrences when it's useful.

For example, if you have a operation that is a rare operation which uses a large object graph, and you know that your going to be "idle" afterwards, you might want to call GC.Collect immediately afterwards to release the memory used by the objects. That being said, this is often still best left up to the system to handle.

For the most part, I've found the most useful scenario for GC.Collect() is for debugging. It can help you guarantee that you don't have a leak, since it allows you to force a full Gen2 collection.

like image 99
Reed Copsey Avatar answered Oct 01 '22 03:10

Reed Copsey


http://blogs.msdn.com/b/ricom/archive/2003/12/02/40780.aspx

http://blogs.msdn.com/b/ricom/archive/2004/11/29/271829.aspx

Right from the equine's oral orifice.

like image 26
dotalchemy Avatar answered Oct 01 '22 02:10

dotalchemy