简体   繁体   中英

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?

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.

正如我所听到的那样,这是一个.Net标准,继承者覆盖基类OnXxxxx方法,用户处理Xxxxx事件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM