Order of disposal for base classes

 ̄綄美尐妖づ 提交于 2019-12-10 16:25:48

问题


When a derived class overrides Dispose should the base class Dipose be called first before the derived class disposes of any local resources?

The reason I ask is because someone on our team is saying yes for every scenario, I'm trying to work out if this is good idea or just 'cargo cult' programming, I don't have a strong view either way.

Before:

 public override void Dispose()
 {
     base.Dispose();

     if (!_isDisposed)
     {
         _isDisposed = true;

         if (_foo != null)
         {
             _foo.Dispose();
         }
     }
 }

After:

 public override void Dispose()
 {
     if (!_isDisposed)
     {
         _isDisposed = true;

         if (_foo != null)
         {
             _foo.Dispose();
         }
     }

     base.Dispose();
 }

Note: I'm not looking for how to implement the basic dispose pattern but more clarification from peoples experiences.


回答1:


"It depends"

You can't have a hard-and-fast rule for this, because the order you need to call dispose will depend on the implementation of the classes.

Sometimes you might want it at the start, sometimes at the end, and sometimes in the middle. Most of the time, it probably won't matter.

Generally speaking, people seem to call it first (in the absence of any other reason to call it at a different time).

One reason to lean towards calling it first is that then the derived class has a chance to do special stuff afterwards if it needs to.




回答2:


You should think about the consequences of the different approaches. In most cases, the IDisposable objects owned by the base class will be independent of those owned by the derived class, and the order of disposal won't matter, provided none of the Dispose methods throws an Exception (*).

If it's critical to release an IDisposable resource, you could consider using try/finally to ensure all Dispose methods are called - but this isn't universally done. For example, the System.Component.Container class manages and disposes multiple IDisposable objects, but makes no attempt to ensure they are all disposed if an exception is thrown.

(*) It's perfectly legitimate for Dispose to throw: for example a FileStream might attempt to flush data to a network resource that's no longer available during Dispose.




回答3:


Dispose object in the reverse order to create. So firstly is created base class, so it should be dispose in the end, and so on...



来源:https://stackoverflow.com/questions/17087621/order-of-disposal-for-base-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!