处置的目的调用在C#中的Dispose(IsDisposing)模式?目的、模式、Dispose、IsDisposing

由网友(场暧昧过后,谁是谁的谁)分享简介:下面是从 MSDN code。我不明白为什么工作不只是在常规Dispose()方法做在这里。具有的Dispose(布尔)方法的目的是什么?谁曾经会调用Dispose(假)在这里?公共无效的Dispose(){处置(真);//使用su pressFinalize的情况下,一个子类//这种类型的实现一个终结。GC.Su...

下面是从 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 实现。如果你正在写一个密封类没有终结,我会去一个简单的实现。

影响Java EE性能的十大问题

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.

阅读全文

相关推荐

最新文章