When should I implement IDisposable?
This question already has an answer here:
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...)
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.
当您的课程在您完成使用时持有您想要释放的资源时,您应该实施IDisposable。
链接地址: http://www.djcxy.com/p/54466.html上一篇: IDisposable接口的主要用途
下一篇: 我应该何时实施IDisposable?