Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: Override OnDispose(bool disposing) vs Disposed event on Component

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?

like image 509
orj Avatar asked Jan 19 '09 01:01

orj


People also ask

What will happen if we call Dispose() method directly?

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.

What happens if Dispose is not called?

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.


3 Answers

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

like image 63
bryanbcook Avatar answered Oct 16 '22 04:10

bryanbcook


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.

like image 40
Spence Avatar answered Oct 16 '22 05:10

Spence


As I ever heard about this matter it is a .Net standard that inheritors override base class OnXxxxx methods and users handle Xxxxx events.

like image 1
Ignacio Soler Garcia Avatar answered Oct 16 '22 05:10

Ignacio Soler Garcia