代码改变世界

[转载].NET Tip: Implement IDisposable to Ensure Your Objects Clean Up After Themselves

  Virus-BeautyCode  阅读(360)  评论(0编辑  收藏  举报
复制代码
public class GoodResourceCitizen : IDisposable
{
    private bool _IsDisposed = false;
    ~GoodResourceCitizen()
    {
        Dispose(false);
    }
    public void Dispose()
    {
        Dispose(true);
        // Tell the garbage collector not to call the finalizer
        // since all the cleanup will already be done.
        GC.SuppressFinalize(true);
    }
    protected virtual void Dispose(bool IsDisposing)
    {
        if (_IsDisposed)
          return;
       if (IsDisposing)
       {
           // Free any managed resources in this section
       }
       // Free any unmanaged resources in this section
       _IsDisposed = true;
    }
}
复制代码

 

 

复制代码
 public class Person:IDisposable
    {
        public int Age { get; set; }

        public override string ToString()
        {

            return base.ToString();
        }
        public Person ShallowClone()
        {

            return base.MemberwiseClone() as Person;
        }

        public Person DeepClone()
        {
            var p = new Person();
            p.Age = this.Age;
            p.Address = new Address() { Detail = this.Address.Detail };
            return p;

        }
        /// <summary>
        /// 析构函数
        /// 自动调用基类的Finalize()释放非托管资源
        /// </summary>
        ~Person()
        {
            //会自动调用base.Finalize();用来释放非托管资源
            Dispose(false);
        }


        public Address Address { get; set; }

        public void Dispose()
        {
            Dispose(true);
            //在上面的Dispose(true)已经释放了非托管资源,所以GC就不能在调用Finalize()方法了,所以需要废除当前对象的Finalize()
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing">是否Dispose方法调用自己</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //release managed resources
            }
            //release unmanaged resources
        }
        
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Human:IDisposable
    {
        ~Human()
        {
            Dispose(false);
     
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //release managed resources
            }

            //release unmanaged resources

        }
    }

    public class Animal 
    {
        ~Animal()
        {
            Dispose(false);

        }

        public void IDisposable.Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //release managed resources
            }

            //release unmanaged resources

        }
        public void Close()
        {
            Dispose(false);
        }
    }

    public class demo
    {
        public void haha()
        {
            var human = new Human();
            human.Dispose();

            var animal = new Animal();
            animal.Close();

            (animal as IDisposable).Dispose();
        }
    }
}
复制代码

 

参考文献

1.C#中Finalize方法的问题

2.Object.Finalize 方法

3.C#中Finalize方法的问题

4.C#中对象的销毁有三种方式Finalize,Dispose,GC。

5.《Effective C#》读书笔记——了解.NET内存管理机制<.NET资源管理>

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示