How to dispose managed resource in Dispose() method in C#?

前端 未结 4 1922
自闭症患者
自闭症患者 2020-12-16 16:33

I know Dispose() is intended for unmanaged resource, and the resource should be disposed when it is no longer needed without waiting for the garbage collector to finalize th

4条回答
  •  清酒与你
    2020-12-16 17:32

    That disposable pattern is confusing. Here's a better way to implement it:

    Step 1. Create a disposable class to encapsulate each unmanaged resource that you have. This should be really rare, most people don't have unmanaged resources to clean up. This class only cares (pdf) about its unmanaged resource, and should have a finalizer. The implementation looks like this:

    public class NativeDisposable : IDisposable {
    
      public void Dispose() {
        CleanUpNativeResource();
        GC.SuppressFinalize(this);
      }
    
      protected virtual void CleanUpNativeResource() {
        // ...
      }
    
      ~NativeDisposable() {
        CleanUpNativeResource();
      }
    
      // ...
    
      IntPtr _nativeResource;
    
    }
    

    Step 2. Create a disposable class when the class holds other disposable classes. That's simple to implement, you don't need a finalizer for it. In your Dispose method, just call Dispose on the other disposables. You don't care about unmanaged resources in this case:

    public class ManagedDisposable : IDisposable {
    
      // ...
    
      public virtual void Dispose() {
        _otherDisposable.Dispose();
      }
    
      IDisposable _otherDisposable;
    
    }
    

    The "Component" in the example would be either one of these, depending on whether it encapsulates an unmanaged resource or if it is just composed of other disposable resources.

    Also note that supressing finalization does not mean you're suppressing the garbage collector from cleaning up your instance; it just means that when the garbage collector runs in your instance, it will not call the finalizer that's defined for it.

提交回复
热议问题