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

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

问题描述

以下是 MSDN 的代码。我不明白为什么这个工作不只是在这里的常规Dispose()方法中完成。使用Dispose(bool)方法的目的是什么?谁会在这里调用Dispose(false)?

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


推荐答案

最终将调用 Dispose(false) - 在这种情况下,您不要触摸任何其他托管资源(可能已经被定稿)。

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).

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

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天全站免登陆