如何正确实现IDisposable [英] How to implement IDisposable properly

查看:198
本文介绍了如何正确实现IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的时间作为一个开发人员试图通过设置变量为空或thier自己的类中调用类上的Dispose()(数据集为例)Dispose()方法来帮助GC一起见过这么多的C#代码
我一直在想,如果有任何需要实现它在托管环境。



这段代码在其设计模式浪费时间吗?

  MyClass类:IDisposable的
{
#地区IDisposable的会员

公共无效的Dispose ()
{
otherVariable = NULL;
如果(数据集!= NULL)
{
dataSet.Dispose();
}
}

#endregion
}


解决方案

在GC的的通话 .Dispose()(它,然而,通话在敲定〜MyClass的()方法,它可以提供给的Dispose()方法的调用自动拥有的资源管理当GC决定要清理你的类)。



您必须提供配置内部资源,如数据集的方式来代码,使用你的类(并确保你实际调用 .Dispose()或包裹构造在使用)。 。使用的IDisposable 在你的类使用内部资源,强烈建议



从的MSDN




主采用此接口的是
释放非托管资源。在
垃圾收集器会自动
释放分配给
管理对象的内存时,该对象没有
不再使用。然而,这不是
可能预测何时发生垃圾
集合。此外,
垃圾收集器具有非托管资源,如窗口
把手,或打开的文件没有知识
和溪流。




 公共无效的Dispose()
{
otherVariable = NULL;
如果(数据集!= NULL)
{
dataSet.Dispose();
数据= NULL;
}
}


I've seen so much C# code in my time as a developer that attempt to help the GC along by setting variables to null or calling Dispose() on classes (DataSet for example) within thier own classes Dispose() method that I've been wondering if there's any need to implement it in a managed environment.

Is this code a waste of time in its design pattern?

class MyClass : IDisposable 
{
    #region IDisposable Members

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

    #endregion
}

解决方案

The GC does not call .Dispose() (It does, however, call the finalize ~MyClass() method, which you can provide a call to the Dispose() method to have resources automatically managed when the GC decides to clean up your class).

You must always provide a way of disposing internal resources such as DataSets to code that uses your classes (and ensure you actually call .Dispose() or wrap the constructor in a using). Using IDisposable on your classes that use internal resources is highly recommended.

From 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;
    }
}

这篇关于如何正确实现IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆