Deterministic dispose of ThreadStatic objects

Spread the love

Question Description

The ThreadStatic attribute declares a static variable as unique-per-thread.
Do you know an easy pattern to correctly dispose such variables?

What we used before ThreadStatic is a ThreadContextManager. Every thread was allocated a ThreadContext which retained all thread-specific information. We spawned some threads and let them work. Then, when they all finished, we disposed of the ThreadContentManager, which in turn disposed all the contexts if they were IDisposable.

I don’t see an immediate way to translate this pattern to ThreadStatic objects. The objects will be disposed of eventualy, because the threads die, and so nothing reference them. However, we prefer deterministic dispose whenever possible.

Update

I do not really control the threads directly – I’m using Microsoft CCR, which has a ThreadPool that does tasks. When all the tasks are done, I’m disposing the Dispatcher (which holds the threadpool). The thing is – I do not get a chance to do anything “at the end of a thread’s main function” – so I can’t dispose things manually at the end of a thread’s run. Can I access the thread’s static objects from outside the thread somehow?

Practice As Follows

You can still use the equivalent of your ThreadContextManager class to handle the dispose. The spawned threads dispose of this ‘manager’ object which in turn takes out all the other thread static objects it knows about.

I prefer to have relatively few thread static objects and use a context object instead. This keeps the thread specific state in only a few places, and makes patterns like this easier.

Update: to handle the threadpool case you could create a base ‘task’ object that is the one that you pass to the thread pool. It can perform any generic initialization your code needs, invoke the ‘real’ task and then performs any cleanup needed.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.