处置的目的调用在C#中的Dispose(IsDisposing)模式? [英] Purpose of Dispose calling Dispose(IsDisposing) pattern in C#?

查看:217
本文介绍了处置的目的调用在C#中的Dispose(IsDisposing)模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是从 MSDN code。我不明白为什么工作不只是在常规Dispose()方法做在这里。具有的Dispose(布尔)方法的目的是什么?谁曾经会调用Dispose(假)在这里?

 公共无效的Dispose()
{
    处置(真);

    //使用su pressFinalize的情况下,一个子类
    //这种类型的实现一个终结。
    GC.Sup pressFinalize(本);
}

受保护的虚拟无效的Dispose(BOOL处置)
{
    //如果需要线程安全,使用围绕这些锁
    //操作,以及在你的方法使用该资源。
    如果(!_disposed)
    {
        如果(处置){
            如果(_resource!= NULL)
                _resource.Dispose();
                Console.WriteLine(对象设置。);
        }

        //表明实例已被释放。
        _resource = NULL;
        _disposed = TRUE;
    }
}
 

解决方案

终结会叫的Dispose(假) - 在这种情况下,你不碰任何的其他管理资源(这可能已经完成)。

我个人不遵循这种模式常常 - 因为我只是非常,很少需要一个终结,而这也是我很少写一个非密封的IDisposable 实现。如果你正在写一个密封类没有终结,我会去一个简单的实现。

Here is code from MSDN. I don't understand why the work isn't just done in the regular Dispose() method here. What is the purpose of having the Dispose(bool) method? Who would ever call Dispose(false) here?

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (_resource != null)
                _resource.Dispose();
                Console.WriteLine("Object disposed.");
        }

        // Indicate that the instance has been disposed.
        _resource = null;
        _disposed = true;   
    }
}

解决方案

The finalizer would call Dispose(false) - in which case you don't touch any of the other managed resources (which may already have been finalized).

Personally I don't follow this pattern often - because I only very, very rarely need a finalizer, and it's also rare for me to write a non-sealed IDisposable implementation. If you're writing a sealed class without a finalizer, I would go for a simple implementation.

这篇关于处置的目的调用在C#中的Dispose(IsDisposing)模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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