Setting a global variable in a thread - C#

.net-4.0, c#, thread-safety

Solution

One solution would be to use a public static field, with the `ThreadStatic` attribute:

[ThreadStatic]
public static int ThreadSpecificStaticValue;

A static field marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value.

Problem

I have an HTTP server that I am writing using HTTP listener, and I would like to somehow declare certain variables as accessible from anywhere within a thread. - My webserver class is instanced based, so I can't really use a static variable. - I could use an instance variable as all of the code is in one class, but...I don't know. I thought of using a dictionary: `Dictionary</*[type of Thread ID here]*/,ThreadData>`, but I'm concerned there might be threading issues. `ThreadData` would probably be a class instance, but I might use a struct, depending on which would be more efficient. - If I would key the dictionary to the Thread IDs and program it so that one thread would only ask for its own entry in the dictionary, would there be any thread-related problems when accessing the dictionary? - Each thread would add its own entry. Would I have to lock the dictionary while I add new thread items? If so, would I be able to use a separate lock object to allow threads to access their own data in the meantime? Would there be an advantage to using a concurrent dictionary? Is there another way that is more thread-safe? I am currently using `ThreadPool.QueueUserWorkItem`. I don't know for sure that this uses a new thread for each item. If not then I could also key it to the context. Update: According to ThreadPool class - MSDN, it does reuse threads. And it does not clear thread data. 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, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread.

Original source

Related problems