views:

349

answers:

3

Are backgroundworker threads re-used?

Specifically, if I set a named data slot (thread-local storage) during the DoWork() method of a backgroundworker, will the value of that data slot persist, potentially to be found be some other thread at a later time?

I wouldn't have thought so, but I have this bug...

EDIT: This blog post suggests that BackGroundWorker utilises a ThreadPool, which implies that Threads are re-used. So the question becomes; do re-used threads potentially persist thread-local storage between invocations?

A: 

Would need to check the source (or via Reflector) to determine this if it is not specified in MSDN.

If it isn't specified you can't rely on the current behaviour not changing in a future version of .NET.

Edit: Looks like it is using the thread pool, so threads will be reused.

Richard
+3  A: 

Well, internally BackgroundWorker is using BeginInvoke which means (I believe) that it is using one of the threads from the ThreadPool. As to if TLS is cleared when threads are returned to the pool, I can't say for certain.

In response to edit, nothing I have seen in Reflector suggests that TLS slots are cleared or freed once returned to the pool. So you have to explicitly clear them before your DoWork method returns.

Sean Bright
A: 

When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, data that is placed in thread local storage by one method can be exposed to any other method that is executed by the same thread pool thread. A method that accesses a field that is marked with the ThreadStaticAttribute attribute could encounter different data depending on which thread pool thread executes it.

source : http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx

scorpio