views:

798

answers:

3

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?

+1  A: 

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.

Rob Walker
I do not want to cleanup after every task. Any given thread in my threadpool does many tasks sequentially. The reason it has context is to save expensive allocation of data structures per task. This means I can only cleanup after all threads are finished.
ripper234
A: 

Thank you for sharing, this is a really handy scenario that many people probably don't know about.

smaclell
A: 

In theory, the CCR could run every task of yours on a separate thread.

So what good is using the Thread Static attribute?

jyoung