20

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?

8 Answers 8

27

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.

1
  • System.Drawing classes do not inform the GC of memory pressure properly, so they are not prioritized for disposal as they should be (it sees a 80mb object as 1k or less) Nov 12, 2011 at 16:26
15

If the object implements IDisposable, you should dispose of it as soon as you are done with it. The easiest way is to surround it with a using block:

using (SqlCommand cmd = new SqlCommand(conn)) {
    cmd.ExecuteNonQuery();
}
6

The reason you should always call Dispose() on any type that implements IDisposable, is that it is usually used to signify that the type acquires unmanaged resources. It is especially important that these are freed, and as early as possible. As others have mentioned, using is the prefered way to do this.

3

There are a couple of ways to look at it. One way tries to figure out if it's really necessary to dispose of an object as soon as it's no longer needed, for example using Reflector to see if it really is holding onto unmanaged resources, or if they were incidentally disposed of anyway. The other perspective is to assume that if an object implements IDisposable, it's not your business to determine if Dispose() really needs to be called--you always call it. I think that is the right way to go. Peeking into the private implementation of objects to make decisions about how you should consume them increases your risk of getting coupled to an implementation that could change. An example is the LINQ to SQL DataContext. It implements IDispose but mostly cleans up after itself without the need for an explicit call to Dispose(). My preference is to write code that explicitly disposes anyway, but others have suggested its not necessary.

Of course this all applies to objects that implement IDisposable. It's true that the GC will take care of most everything else without any explicit action on your part, but it's worth reading up a bit on the subtleties of GC behavior (I'm too tired to think of the details right now) to know when to dispose of objects explicitly, and more importantly, when to implement IDispose. There are lots of good articles on the interwebs on the matter.

And as said previously, using(..) { ... } is your friend for IDisposable implementors.

0
1

If the object implemented IDisposable, it is quite likely that it is holding on to unmanaged resources. The rule of thumb, therefore, would be to call Dispose the moment you are done with the object, either directly or via a using block. Don't rely on the GC, since that's what the IDisposable is for - deterministic release of resources.

0

No you can get away with calling Dispose in the cases where you are not holding an unmanaged resource. But if your class is holding an unmanaged resource say, a temp file that needs to be deleted, then you will have to explicitly call Dispose.

You can avoid calling Dispose by writing your freeing code in Finalize method but then you are dependent on the Garbage Collector because you are never sure than when Garbage collector will finalize your object. To be on the safe side, if you are designing such a class which holds an unmanaged resource, you can write the same object-freeing code in both Dispose And Finalize method but if you do so, always use SuppressFinalize() in your dispose method because it will prevent the Finalize() method from being called if your object is already on the Finalization Queue.

1
-1

Relying on the GC 'works' in most instances. The classic exception is when you have a resource heavy interaction - in that instance it is best to explicilty dispose.

obvious eg.

using (var conn = new SqlConnection(connString)) {}

'Using' blocks are definitely the cleanest and most robust method of ensuring that objects are disposed of correctly. 'Using' blocks can be leveraged with any objects that implements IDisposable.

8
  • The GC works on it's own purely by coincidence. It is under no obligation to call Dispose in a timely manner.
    – JaredPar
    Oct 29, 2008 at 5:50
  • I didn't suggest that the GC was obliged to do it in a timely manner. I stand by my claim that manaul disposal of regular objects is unnecessary.
    – berko
    Oct 30, 2008 at 22:31
  • So, for example, when you create a Bitmap instance, you don't think you need to dispose it manually? Think again. The GC sees that 30MB object as 10 bytes and ignores it indefinitely. It will crash your server Every Single Time. Nov 2, 2011 at 14:43
  • WPF avoids this using artificial GC pressure estimations for unmamaged objects, but has other bugs that make it unsupported on the server. Nov 12, 2011 at 16:25
  • While, personally, I generally try to dispose when I'm done (like berko says, using blocks...), there's nothing wrong with this answer, as he's right that in non-resource intensive situations (you can use IDisposable for cases OTHER than unsafe data) it's generally not too important. I think he was making the point that it's a judgement call. In MOST cases, wrapping in a 'using' will be the right call, but what about if it's being passed around the place (esp. to different threads)? @Computer Linguist - coming in 3 years after an answer with comments like 'crash your server EST' is inflamatory Nov 22, 2011 at 0:22
-7

When you're done with an object you can forget about it. As long as it's not referenced anywhere then it's as good as gone. The memory it uses is freed up when the garbage collector feels like it.

2
  • Can someone please explain WHY this answer was slammed like this? -6? And no commments?
    – bobobobo
    Aug 8, 2009 at 3:36
  • 4
    @bobobobo I think because it is not addressing IDisposable which is intended to allow an object to release resources external to the .NET runtime when they are no longer needed instead of waiting for GC. Oct 16, 2009 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.