以下是有关这我不清楚一个例子:如何正确处理来自终结器的非托管资源的收集?
public class SomeClass : IDisposable {
~SomeClass() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
protected virtual void Dispose(bool disposing) {
if (!_disposed) {
if (disposing) {
// TODO: Release any managed resources here...
}
// ?! Is it safe to enumerate the dictionary here ?!
foreach (var resource in _resources.Values)
ReleaseBuffer(resource);
_resources = null;
_disposed = true;
}
}
private Dictionary<string, IntPtr> _resources;
...
}
会不会是安全的枚举管理字典,以释放非托管资源?
由于未定义终结器的顺序,因此字典的可用性是否不确定?
这里是从MSDN截取的报价,我感到迷惑[1]:即使一个对象指的是
- 两个对象的终结不能保证在任何特定的顺序运行,其他。也就是说,如果对象A具有对象B的引用并且都具有终结器,则在对象A的终结器开始时,对象B可能已经完成。
它应该是安全的,字典是一个管理对象,根植于您的类的实例,它将被访问,直到调用终结器。请参阅http://stackoverflow.com/questions/13954829/gc-collect-and-finalize。 – galenus 2014-10-30 19:42:24
'Dictionary'没有终结符。所以你很安全。 – Blorgbeard 2014-10-30 19:43:41
@Blorgbeard:字典不是线程安全的,对于运行终结器的线程上下文没有任何保证。 – supercat 2014-10-31 20:24:27