c# – 如何正确实现IDisposable

前端之家收集整理的这篇文章主要介绍了c# – 如何正确实现IDisposable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我作为一个开发人员的时候,我已经看到过这么多的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;
    }
}
原文链接:https://www.f2er.com/csharp/94993.html

猜你在找的C#相关文章