BlockingCollection<T>类的Documentation有如下说明:
Always call Dispose before you release your last reference to the
BlockingCollection<T>. Otherwise, the resources it is using will not be freed
until the garbage collector calls the BlockingCollection<T> object's Finalize
method.C#中BlockingCollection<T>的internal implementation有如下方法:
/// <summary>
/// Releases resources used by the <see cref="T:System.Collections.Concurrent.BlockingCollection{T}"/> instance.
/// </summary>
/// <param name="disposing">Whether being disposed explicitly (true) or due to a finalizer (false).</param>
protected virtual void Dispose(bool disposing)在调用之后,只有一次使用参数disposing: true和finalization suppress调用此Dispose。但是,令我惊讶的是,该类中没有显式的终结器,甚至没有调用Dispose(false)。看起来Dispose函数相对简单,它只是删除了对不同对象的引用,以提高GC速度。在这种情况下,当我们忘记显式调用Dispose()时,GC将为我们做这项工作。
有人能发现这个类内部的亮点吗?方法Dispose(bool disposing)的用途是什么?即使在不需要的情况下,为.NET核心库实现此方法也是常见的做法吗?
发布于 2019-05-24 07:26:26
我认为关于如何正确实现dispose模式的MSDN documentation值得一读。但是,您的问题的答案是BlockingCollection不是密封的。这意味着它可以被派生出来。使用void Dispose(bool disposing)的原因是允许派生类正确地释放基类的资源。因此,例如,我可以实现
class Foo : BlockingCollection<string>
{
private bool disposed = false;
~Foo()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
// free managed resources
}
// free unmanaged resources
disposed = true;
base.Dispose(disposing);
}
}通过这样做,当Dispose()被调用时,BlockingCollection将在Foo上调用Dispose(true),这最终将在BlockingCollection上调用Dispose(true),您将获得~Foo()终结器被抑制的好处。如果未调用Dispose()方法,则不会取消终结器,而是调用该终结器,从而允许Foo仍然释放其非托管资源。
https://stackoverflow.com/questions/56271359
复制相似问题