Search code examples
c#.netmultithreadingthread-local

Memory concerns and ThreadLocal<T>


I noticed that ThreadLocal<T> implements IDisposable, implying I should dispose of a thread-local variable when I'm done using it. I'm just curious what the specific concerns are and what I should be careful to do and/or avoid doing.

Will a thread's local storage be disposed of when the thread exits? What's the worst case if I don't dispose of my ThreadLocal members?

What if I have a global thread-local (oxymoron? hehe) variable (or alternatively a ThreadStatic variable) and I assign this value on threads in the ThreadPool. Do I have to be careful to de-allocate thread-local values, or is that not a concern?


Solution

  • I don't believe that thread locals are automatically disposed by a thread when it exists - that is still left to the developer to implement. From MSDN:

    Always call Dispose before you release your last reference to the ThreadLocal. Otherwise, the resources it is using will not be freed until the garbage collector calls the ThreadLocal object's Finalize method.

    However, if your thread local type is something that does not consume any resources that warrant disposable (an int or other primitive type, for instance) it probably ok not to dispose it as the garbage collector will eventually deal with it.

    It's generally unwise to have the same instance of an object references by multiple ThreadLocal objects - in fact, it's against the grain of what thread-local storage generally seeks to accomplish. Isolated thread locals can be assumed to be "thread safe" - in the sense that no other threads should (in principle) have access to them. Keep in mind that thread safety is a nuanced concept and requires that you establish specific constraints and expectations about shared memory ... I'm using the term in this context in a loose sense.