抛出未处理的异常时应调用Dispose吗?

时间:2019-04-25 07:25:10

标签: c# dispose

假设我有一个类似如下的课程:

public class DisposableClass : IDisposable()
{
   private readonly Timer timer;

   DisposableClass()
   {
      this.timer = new Timer(s => cb(s), s, 1000, 1000);
   }

   Init()
   {
       try
       {
           // Do some initialization here that is not done in ctor.
       }
       catch (Exception)
       {
          // Log error.
          throw;
       }
       finally
       {
           // Is this correct?
           this.Dispose();
       }
   }

    public void Dispose()
    {
        this.timer?.Dispose();
    }
}

我的问题是,在抛出未处理异常时,对于任何非构造方法,上述情况下的finally子句是否必要(或根本不需要)。谢谢。

编辑:

在回答中,请根据Init()publicprotected可见度级别private来解决问题。

0 个答案:

没有答案