Should “Dispose” only be used for types containing unmanaged resources?

后端 未结 15 1608
执笔经年
执笔经年 2020-12-05 01:41

I was having a discussion with a colleague recently about the value of Dispose and types that implement IDisposable.

I think there is value

相关标签:
15条回答
  • 2020-12-05 02:11

    If you aggregate IDisposables then you should implement the interface in order that those members get cleaned up in a timely way. How else is myConn.Dispose() going to get called in the ADO.Net connection example you cite?

    I don't think it's correct to say that everything is an unmanaged resource in this context though. Nor do I agree with your colleague.

    0 讨论(0)
  • 2020-12-05 02:19

    Not necessary resources at all (either managed or unmanaged). Often, IDisposable is just a convenient way to elimnate combersome try {..} finally {..}, just compare:

      Cursor savedCursor = Cursor.Current;
    
      try {
        Cursor.Current = Cursors.WaitCursor;
    
        SomeLongOperation();
      }
      finally {
        Cursor.Current = savedCursor;
      }
    

    with

      using (new WaitCursor()) {
        SomeLongOperation();
      }
    

    where WaitCursor is IDisposable to be suitable for using:

      public sealed class WaitCursor: IDisposable {
        private Cursor m_Saved;
    
        public Boolean Disposed {
          get;
          private set;
        }
    
        public WaitCursor() {
          Cursor m_Saved = Cursor.Current;
          Cursor.Current = Cursors.WaitCursor;
        }
    
        public void Dispose() {
          if (!Disposed) {
            Disposed = true;
            Cursor.Current = m_Saved;
          }
        }
      }
    

    You can easily combine such classes:

      using (new WaitCursor()) {
        using (new RegisterServerLongOperation("My Long DB Operation")) {
          SomeLongRdbmsOperation();  
        }
    
        SomeLongOperation();
      }
    
    0 讨论(0)
  • 2020-12-05 02:19

    Implement IDisposable if the object owns any unmanaged objects or any managed disposable objects

    If an object uses unmanaged resources, it should implement IDisposable. The object that owns a disposable object should implement IDisposable to ensure that the underlying unmanaged resources are released. If the rule/convention is followed, it is therefore logical to conclude that not disposing managed disposable objects equals not freeing unmanaged resources.

    0 讨论(0)
提交回复
热议问题