Handling IDisposable in failed initializer or constructor

前端 未结 5 532
名媛妹妹
名媛妹妹 2020-12-11 06:34

Is there any nice pattern in .Net for ensuring that IDisposable fields owned by an object will get disposed if an exception is thrown during construction, possi

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 06:55

    You should catch any exceptions in the constructor, then dispose of your child objects, then rethrow the original exception (or a new exception that provides additional information).

    public class SomethingDisposable : IDisposable
    {
      System.Diagnostics.Process disposableProcess;
      public SomethingDisposable()
      {
        try
        {
          disposableProcess = new System.Diagnostics.Process();
          // Will throw an exception because I didn't tell it what to start
          disposableProcess.Start();
        }
        catch
        {
          this.Dispose();
          throw;
        }
      }
    
      public void Dispose()
      {
        if (disposableProcess != null)
        {
          disposableProcess.Dispose();
          disposableProcess = null;
        }
      }
    }
    

提交回复
热议问题