为什么我们需要的参数配置在下面的代码片段.
此外,我们在终结器中使用false来调用dispose,它不会释放或进行清理.
那么如果处置永远不会被召唤怎么办?
在终结器之前总是被调用吗?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
**//Do we really need this condition?
if (disposing)**
{
// called via myClass.Dispose().
// OK to use any private object references
}
disposed = true;
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
Run Code Online (Sandbox Code Playgroud)
换句话说为什么不呢?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool suppressFinalize)
{
if (!disposed)
{
//Do we really need this condition?
// called via myClass.Dispose().
// OK to use any private object references
disposed = true;
}
if (!suppressFinalize)
{
GC.SuppressFinalize(this);
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
Run Code Online (Sandbox Code Playgroud)
事实上,我真的需要终结者吗?为什么不呢?
using System;
public class MyClass : IDisposable
{
public void Dispose()
// Implement IDisposable
{
//just do the cleanup and release resources
GC.SuppressFinalize(this);
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 10
此外,我们在终结器中使用false来调用dispose,它不会释放或进行清理.
确实 - 在这种情况下,它会假设其他类处理自己的清理,并且只清理直接的非托管资源.
那么如果处置永远不会被召唤怎么办?
然后将调用终结器,它将清除任何直接的非托管资源,但不担心间接资源.
在终结器之前总是被调用吗?
如果没有人因为某种原因召唤它,那就不行了.
我认为这种模式比它需要的更复杂,因为它试图考虑作为可能需要终结器的其他类的基类的类.密封你的课程,你可以完全实现你期望的:)
您可能还想阅读Joe Duffy的"Never again a finalizer again"博客文章和模式的长篇解释.