In .Net the Component
class exposes a Disposed
event. It also provides a protected member OnDispose(bool disposing)
.
What is the best practice for a custom component that extends Component
? Override OnDispose(bool)
or attach an event handler to Disposed
on construction?
My feeling is that one should override OnDispose(bool)
and seal the class.
Thoughts?
The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
Implement a finalizer to free resources when Dispose is not called. By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
Typically events are used by consumers so that they can be notified when events occur. If you're extending the Type and need to clean up resources you should override Dispose(bool disposing)
Spence is partly right about the Event handler, multiple events can be assigned but the issue is that you can't guarantee the order in which the Events are handled.
Sealing the class often depends on what you're designing.
The FxCop rule also has some good info: http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx
I would recommend overriding the behaviour, as an implementer of your component has access to the event handler and as such could deregister your disposer implementation by accident. I believe that you may also need to do this depending on what your custom component is doing, as you may need to run your disposing tasks before calling to the base disposer if you have stateful objects or external interfaces etc.
As I ever heard about this matter it is a .Net standard that inheritors override base class OnXxxxx methods and users handle Xxxxx events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With