其他分享
首页 > 其他分享> > CodeGo.net>使用一次性模式来清理IDispose成员类

CodeGo.net>使用一次性模式来清理IDispose成员类

作者:互联网

一次性图案的一部分包括以下方法.

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的类成员该怎么办?

通常,我不知道该成员是否清理托管或非托管资源.因此,如果我希望我的Dispose方法清理实现IDisposable的类成员,我可以在上面代码的托管部分或非托管部分中的该成员上调用Dispose()吗?

解决方法:

您应该在受管部分中调用“处置”(即,仅当处置为true时).

框架设计指南中的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,dispose,c
来源: https://codeday.me/bug/20191028/1949065.html