什么是在C#中实现IDisposable的正确方法?

这个问题在这里已经有了答案:

  • 正确使用IDisposable接口18的答案

  • 你可以在这里找到很好的解释。正确使用IDisposable接口

    简短的例子:

    public void Dispose() {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    private void Dispose(bool disposing) {
        if (!this.disposed) {
            if (disposing) {
                // clean resources here
            }
            disposed = true;
        }
    }
    
    private bool disposed = false;
    

    我认为这是或多或少的标准模板:

        private bool disposed = false;
    
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
    
        protected virtual void Dispose(bool disposing)
        {
    
            if(!disposed)
            {
    
                if(disposing)
                {
                    // destroy managed objects here...
                }
    
                disposed = true;
            }
        }
    
    
        ~NameOfClass()
        {
            Dispose(false);
        }
    

        public class MyResource: IDisposable
        {
            // Pointer to an external unmanaged resource. 
            private IntPtr handle;
            // Other managed resource this class uses. 
            private Component component = new Component();
            // Track whether Dispose has been called. 
            private bool disposed = false;
    
            public MyResource(IntPtr handle)
            {
                this.handle = handle;
            }
    
            public void Dispose()
            {
                Dispose(true);            
                GC.SuppressFinalize(this);
            }
    
            protected virtual void Dispose(bool disposing)
            {
                if(!this.disposed)
                {
                   if(disposing)
                    {
                        // Dispose managed resources.
                        component.Dispose();
                    }
    
                    CloseHandle(handle);
                    handle = IntPtr.Zero;
    
                    // Note disposing has been done.
                    disposed = true;
    
                }
            }
    
            // Use interop to call the method necessary 
            // to clean up the unmanaged resource.
            [System.Runtime.InteropServices.DllImport("Kernel32")]
            private extern static Boolean CloseHandle(IntPtr handle);
    
            ~MyResource()
            {
                // Do not re-create Dispose clean-up code here. 
                // Calling Dispose(false) is optimal in terms of 
                // readability and maintainability.
                Dispose(false);
            }
        }
    

    来源 :IDisposable接口

    链接地址: http://www.djcxy.com/p/54481.html

    上一篇: What is the correct way to implement IDisposable in C#?

    下一篇: Implement IDisposable in abstract class