Proper use of the IDisposable interface

后端 未结 19 3323
情深已故
情深已故 2020-11-21 04:05

I know from reading the Microsoft documentation that the \"primary\" use of the IDisposable interface is to clean up unmanaged resources.

To me, \"unman

19条回答
  •  遇见更好的自我
    2020-11-21 04:50

    First of definition. For me unmanaged resource means some class, which implements IDisposable interface or something created with usage of calls to dll. GC doesn't know how to deal with such objects. If class has for example only value types, then I don't consider this class as class with unmanaged resources. For my code I follow next practices:

    1. If created by me class uses some unmanaged resources then it means that I should also implement IDisposable interface in order to clean memory.
    2. Clean objects as soon as I finished usage of it.
    3. In my dispose method I iterate over all IDisposable members of class and call Dispose.
    4. In my Dispose method call GC.SuppressFinalize(this) in order to notify garbage collector that my object was already cleaned up. I do it because calling of GC is expensive operation.
    5. As additional precaution I try to make possible calling of Dispose() multiple times.
    6. Sometime I add private member _disposed and check in method calls did object was cleaned up. And if it was cleaned up then generate ObjectDisposedException
      Following template demonstrates what I described in words as sample of code:

    public class SomeClass : IDisposable
        {
            /// 
            /// As usually I don't care was object disposed or not
            /// 
            public void SomeMethod()
            {
                if (_disposed)
                    throw new ObjectDisposedException("SomeClass instance been disposed");
            }
    
            public void Dispose()
            {
                Dispose(true);
            }
    
            private bool _disposed;
    
            protected virtual void Dispose(bool disposing)
            {
                if (_disposed)
                    return;
                if (disposing)//we are in the first call
                {
                }
                _disposed = true;
            }
        }
    

提交回复
热议问题