加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何正确实现IDisposable

发布时间:2020-12-15 06:41:31 所属栏目:百科 来源:网络整理
导读:在我作为一个开发人员的时候,我已经看到过这么多的C#代码,试图通过将变量设置为null来帮助GC,或者在它们自己的类之间的类(DataSet)上调用Dispose()Dispose()方法 我一直在想,是否有必要在受管理的环境中实现它. 这个代码在设计模式中是否浪费时间? class My
在我作为一个开发人员的时候,我已经看到过这么多的C#代码,试图通过将变量设置为null来帮助GC,或者在它们自己的类之间的类(DataSet)上调用Dispose()Dispose()方法
我一直在想,是否有必要在受管理的环境中实现它.

这个代码在设计模式中是否浪费时间?

class MyClass : IDisposable 
{
    #region IDisposable Members

    public void Dispose() 
    {
        otherVariable = null;
        if (dataSet != null)
        {
            dataSet.Dispose();
        }
    }

    #endregion
}

解决方法

GC不调用.Dispose()(但是,它调用finalize?MyClass()方法,可以提供对Dispose()方法的调用,以便在GC决定清理类时自动管理资源).

您必须始终提供一种处理内部资源(例如DataSet)的方式来使用您的类的代码(并确保您实际调用.Dispose()或将构造函数包含在使用中).强烈建议您在使用内部资源的课程上使用IDisposable.

从MSDN:

The primary use of this interface is
to release unmanaged resources. The
garbage collector automatically
releases the memory allocated to a
managed object when that object is no
longer used. However,it is not
possible to predict when garbage
collection will occur. Furthermore,
the garbage collector has no knowledge
of unmanaged resources such as window
handles,or open files and streams.

public void Dispose()
{
    otherVariable = null;
    if (dataSet != null)
    {
        dataSet.Dispose();
        dataSet = null;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读