Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is thread-local storage persisted between backgroundworker invocations?

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?

like image 200
Ed Guiness Avatar asked Feb 18 '09 15:02

Ed Guiness


People also ask

Is BackgroundWorker threaded?

BackgroundWorker, is a component in . NET Framework, that allows executing code as a separate thread and then report progress and completion back to the UI.

What is Threadlocal C#?

Thread Local Storage is used to store thread-specific pieces of data. Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. All threads of a process share the virtual address space of the process.


1 Answers

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

https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadpool?redirectedfrom=MSDN&view=netframework-4.8#remarks

like image 160
scorpio Avatar answered Oct 24 '22 15:10

scorpio