Memory Issues and ThreadLocal <T>
I noticed that ThreadLocal<T> implements IDisposable , implying that I have to dispose of the local thread variable when I do this. I am just wondering what specific problems are and what I should do carefully and / or avoid.
Will the local thread store be deleted when the stream exits? What's the worst case if I don't get rid 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 to threads in ThreadPool. Should I be careful not to allocate local thread values ββor is this not a problem?
I do not believe that stream locators are automatically deleted by the stream when it exists, and this still remains for the developer to implement. From MSDN:
Always call Dispose before you release your last ThreadLocal link. Otherwise, the resources that it uses will not be freed until the garbage collector calls the Finalize method of the ThreadLocal object.
However, if your local stream type is something that does not consume any resources that guarantee a one-time (for example, int or other primitive type), you probably should not destroy it, since the garbage collector will eventually cope with it.
As a rule, it is unreasonable to have the same instance of object references by several ThreadLocal objects - in fact, this is against the grain of what local storage usually tries to do. Isolated flow locators can be considered "thread safe" - in the sense that no other thread should (in principle) have access to them. Keep in mind that thread safety is a subtle concept and requires that you set certain limits and expectations regarding shared memory ... I use this term in this context in a free sense.