使用一次性模式清理 IDispose 成员 类

Using Disposable Pattern to Clean Up IDispose Member Classes

部分一次性花样包括以下方法

protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
        disposed = true;
    }
}

此方法对清理托管和非托管资源有不同的处理方式。但是,如果我想清理实现 IDisposable 的 class 成员怎么办?

通常情况下,我不知道该成员是清理托管资源还是非托管资源。因此,如果我希望我的 Dispose 方法清理实现 IDisposable 的 class 成员,我是否会在上面代码的托管或非托管部分中对该成员调用 Dispose()

您应该在托管部分调用 Dispose(即,仅当 disposing 为真时)。

框架设计指南Dispose Pattern中的部分指南是:

The Boolean parameter disposing indicates whether the method was invoked from the IDisposable.Dispose implementation or from the finalizer. The Dispose(bool) implementation should check the parameter before accessing other reference objects [...]. Such objects should only be accessed when the method is called from the IDisposable.Dispose implementation (when the disposing parameter is equal to true). If the method is invoked from the finalizer (disposing is false), other objects should not be accessed. The reason is that objects are finalized in an unpredictable order and so they, or any of their dependencies, might already have been finalized.

另一个有用的资源是 Implementing a Dispose Method

配置实现IDisposable的class成员的标准方式是这样的:

public class Foo : IDisposable
{
    // MemoryStream implements IDisposable
    private readonly Stream _stream = new MemoryStream();

    private bool _disposed;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            _stream.Dispose();
        }

        _disposed = true;
    }
}

澄清一下,清理 managed 资源意味着资源本身实现了 IDisposable(正如上面的 MemoryStream 所做的那样)。 MemoryStream/Stream 持有底层 unmanaged 资源,其清理逻辑已经为您实现。无需清理 Foo.

中的 unmanaged 资源