When should I dispose my objects in .NET?

danmine picture danmine · Oct 29, 2008 · Viewed 15.4k times · Source

For general code, do I really need to dispose an object? Can I just ignore it for the most part or is it a good idea to always dispose an object when your 100% sure you don't need it anymore?

Answer

JaredPar picture JaredPar · Oct 29, 2008

Dispose of an object the instant your are done with it. Disposable objects represent objects holding a valuable resource which the CLR is not intrinsically aware of. Consequently the GC is also unaware of the resources and is unable to make intelligent decisions as to when it should collect a disposable object and hence free the underlying resource.

Eventually the GC will feel memory pressure and collect your object by coincidence (nothing more). If you don't dispose of objects in a deterministic manner then it is completely possible to enter a resource starved state with almost no memory pressure.

Quick example of how this can happen. Lets think of the underlying resource as Win32 handle. These are very finite and fairly small. You run an operation that create a lot of Foo objects. Foo objects implement IDisposable and are responsible for creating and disposing of a Win32 handle. They are not manually freed and by a difference quirk make it into the Gen2 heap. This heap is freed fairly infrequently. Over time enough Foo instances make it into the Gen2 heap to take up all of the available handles. New Foo objects are consequently unable to be created regardless of how much memory is being used.

In fact to free the handles, it would take a rather large amount of memory to be allocated during a single operation to give enough pressure to free the instances.