Use of Finalize/Dispose method in C#

后端 未结 13 2060
轮回少年
轮回少年 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:27

    Dispose pattern:

    public abstract class DisposableObject : IDisposable
    {
        public bool Disposed { get; private set;}      
    
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        ~DisposableObject()
        {
            Dispose(false);
        }
    
        private void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    DisposeManagedResources();
                }
    
                DisposeUnmanagedResources();
                Disposed = true;
            }
        }
    
        protected virtual void DisposeManagedResources() { }
        protected virtual void DisposeUnmanagedResources() { }
    }
    

    Example of inheritance:

    public class A : DisposableObject
    {
        public Component components_a { get; set; }
        private IntPtr handle_a;
    
        protected override void DisposeManagedResources()
        {
            try
            {
              Console.WriteLine("A_DisposeManagedResources");
              components_a.Dispose();
              components_a = null;
            }
            finally
            { 
              base.DisposeManagedResources();
            }
        }
    
        protected override void DisposeUnmanagedResources()
        {
            try
            {
              Console.WriteLine("A_DisposeUnmanagedResources");
              CloseHandle(handle_a);
              handle_a = IntPtr.Zero;
            }
            finally
            { 
              base.DisposeUnmanagedResources();
            }
        }
    }
    
    public class B : A
    {
        public Component components_b { get; set; }
        private IntPtr handle_b;
    
        protected override void DisposeManagedResources()
        {
            try
            {
              Console.WriteLine("B_DisposeManagedResources");
              components_b.Dispose();
              components_b = null;
            }
            finally
            { 
              base.DisposeManagedResources();
            }
        }
    
        protected override void DisposeUnmanagedResources()
        {
            try
            {
              Console.WriteLine("B_DisposeUnmanagedResources");
              CloseHandle(handle_b);
              handle_b = IntPtr.Zero;
            }
            finally
            { 
              base.DisposeUnmanagedResources();
            }
        }
    }
    

提交回复
热议问题