当您使用
根据 ILSpy 的分析,ThreadLocal 的 Dispose() 和 Dispose(bool) 方法如下:
ThreadLocal<T>
,且 T
实现了 IDisposable 接口时,您应该如何处理 ThreadLocal 中持有的成员的处理?根据 ILSpy 的分析,ThreadLocal 的 Dispose() 和 Dispose(bool) 方法如下:
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
int currentInstanceIndex = this.m_currentInstanceIndex;
if (currentInstanceIndex > -1 && Interlocked.CompareExchange(ref this.m_currentInstanceIndex, -1, currentInstanceIndex) == currentInstanceIndex)
{
ThreadLocal<T>.s_availableIndices.Push(currentInstanceIndex);
}
this.m_holder = null;
}
ThreadLocal似乎不会尝试调用其子成员的Dispose。我无法确定如何引用它内部分配的每个线程,以便我可以处理它。
我使用以下代码运行了一个测试,该类从未被销毁。
static class Sandbox
{
static void Main()
{
ThreadLocal<TestClass> test = new ThreadLocal<TestClass>();
test.Value = new TestClass();
test.Dispose();
Console.Read();
}
}
class TestClass : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool Disposing)
{
Console.Write("I was disposed!");
}
}
ThreadLocal
跟踪所有Value
,这使得手动处理它们变得容易:.NET 4.5 中的新功能:ThreadLocal.Values - Sphinxxx