Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I implement IDisposable? [duplicate]

What is the best practice for when to implement IDisposable?

Is the best rule of thumb to implement it if you have one managed object in the class, or does it depend if the object was created in the class or just passed in? Should I also do it for classes with no managed objects at all?

like image 680
Bobby Avatar asked Mar 12 '10 09:03

Bobby


People also ask

When should you implement IDisposable?

in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed. If not, this responsibility is left to the garbage collector to free the memory when the object containing the unmanaged resources is finalized.

Which of these are the reason for implementing IDisposable interface?

If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there.

Why do we need IDisposable?

You never know when the garbage collector will collect your object. You don't even know if it even will (unlike using delete in C++, which is deterministic). So IDisposable is there for deterministically releasing unneeded references (and releasing unmanaged resources).

What happens if you dont Dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.


2 Answers

If you mean unmanaged objects then yes, you should be implementing it whenever you have one or more unmanaged resource you are handling in your class. You should also be using the pattern when you are possibly holding on to objects that are IDisposable themselves, and make sure to dispose of them when your class is disposed.

(agreed that this question has already been asked enough times as to run a small printer out of ink should they be printed...)

like image 70
peppy Avatar answered Oct 07 '22 19:10

peppy


While everyone has mentioned (unmanaged) resources, I have another thing to add: I use it when I need to eliminate event handler hookups that would otherwise prevent a class from going out of scope and being garbage collected.

As an example, I have a service which gets injected in to a child view, that child view will subscribe to various async finished type events on the service. The owner of that child view has no idea what the concrete type is, it simply has it as an interface. The service may go out of scope at some arbitrary point in the future, and I don't want it hanging around not being GC'ed. Upon getting rid of that child view, the owner will call Dispose on it to give it the chance to unhook any event handlers. Here is a slightly contrived (and very pseudo code) example, note how the interface for the child view also implements IDisposable.

public class OwnerView {      public OwnerView() {         _childView = new ChildView(myServiceReference);     }      public void CloseChildView() {         if (childView != null) {             _childView.Close();             _childView.Dispose();         }          _childView = null;     }      private IChildView _childView; }  public class ChildView : IChildView {      public ChildView(MyService serviceRef) {         _serviceRef = serviceRef;         _serviceRef.GetSettingsAsyncFinished += new EventHandler(someEventHandler);     }      public void IDisposable.Dispose() {         _serviceRef -= someEventHandler;     }      private MyService _serviceRef; }  public interface IChildView : IDisposable {     void DoSomething();     ... etc ... } 

There are far more authoritative comments about this from others on SO, like Do event handlers stop garbage collection from occuring? and Garbage collection when using anonymous delegates for event handling. You may also want to check out this codeproject article.

like image 35
slugster Avatar answered Oct 07 '22 18:10

slugster