title: What is the correct way to dispose elements held inside a ThreadLocal<IDisposable>?
body: <p>When you use a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadlocal-1" rel="nofollow noreferrer"><code>ThreadLocal&lt;T&gt;</code></a> and <code>T</code> implements IDisposable, how are you supposed to dispose of the members being held inside of the ThreadLocal?</p>
  
  <p>According to ILSpy, the Dispose() and Dispose(bool) methods of ThreadLocal are</p>
  
  <pre><code>public void Dispose()
  {
      this.Dispose(true);
      GC.SuppressFinalize(this);
  }
  
  protected virtual void Dispose(bool disposing)
  {
      int currentInstanceIndex = this.m_currentInstanceIndex;
      if (currentInstanceIndex &gt; -1 &amp;&amp; Interlocked.CompareExchange(ref this.m_currentInstanceIndex, -1, currentInstanceIndex) == currentInstanceIndex)
      {
          ThreadLocal&lt;T&gt;.s_availableIndices.Push(currentInstanceIndex);
      }
      this.m_holder = null;
  }
  </code></pre>
  
  <p>It does not appear that ThreadLocal attempts to call Dispose on its child members. I can't tell how to reference each thread it internally has allocated so I can take care of it.</p>
  
  <hr>
  
  <p>I ran a test with the following code, the class is never disposed</p>
  
  <pre><code>static class Sandbox
  {
      static void Main()
      {
          ThreadLocal&lt;TestClass&gt; test = new ThreadLocal&lt;TestClass&gt;();
          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!");
      }
  }
  </code></pre>