Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the IDisposable interface work?

I understand that it is used to deallocate unmanaged resources, however, I am confused as to when Dispose is actually called. I know it is called at the end of a using block, but does it also get invoked when the object is garbage collected?

like image 636
Tony the Pony Avatar asked Mar 10 '09 19:03

Tony the Pony


1 Answers

If you implement IDisposable correctly, you should also include a finalizer that will call Dispose() on your object.

If you do that, it will get called by the GC. However, it's still a VERY good idea to try to always dispose of these objects yourself.

The biggest problem with relying on the finalizer to call Dispose is that it will happen in another thread which you don't control. This can have nasty consequences in certain situations, including causing an exception that's happening in the GC thread, which is not good, as well as having a disposed field you check. This is also part of why including GC.SuppressFinalize(this) in your Dispose() method is important - once an object's disposed, you don't want to re-dispose it.

like image 152
Reed Copsey Avatar answered Sep 20 '22 18:09

Reed Copsey