Use of Finalize/Dispose method in C#

后端 未结 13 2093
轮回少年
轮回少年 2020-11-21 23:20

C# 2008

I have been working on this for a while now, and I am still confused about the use of finalize and dispose methods in code. My questions are below:

13条回答
  •  故里飘歌
    2020-11-21 23:42

    Pattern from msdn

    public class BaseResource: IDisposable
    {
       private IntPtr handle;
       private Component Components;
       private bool disposed = false;
       public BaseResource()
       {
       }
       public void Dispose()
       {
          Dispose(true);      
          GC.SuppressFinalize(this);
       }
       protected virtual void Dispose(bool disposing)
       {
          if(!this.disposed)
          {        
             if(disposing)
             {
                Components.Dispose();
             }         
             CloseHandle(handle);
             handle = IntPtr.Zero;
           }
          disposed = true;         
       }
       ~BaseResource()      
       {      Dispose(false);
       }
       public void DoSomething()
       {
          if(this.disposed)
          {
             throw new ObjectDisposedException();
          }
       }
    }
    public class MyResourceWrapper: BaseResource
    {
       private ManagedResource addedManaged;
       private NativeResource addedNative;
       private bool disposed = false;
       public MyResourceWrapper()
       {
       }
       protected override void Dispose(bool disposing)
       {
          if(!this.disposed)
          {
             try
             {
                if(disposing)
                {             
                   addedManaged.Dispose();         
                }
                CloseHandle(addedNative);
                this.disposed = true;
             }
             finally
             {
                base.Dispose(disposing);
             }
          }
       }
    }
    

提交回复
热议问题