Is there any way to have ThreadStatic variables be transferred from one thread to another? I have a bunch of ThreadStatic variables, and now that I am converting my operation to be asynchronous, I want to be able to "transfer" them from the first thread (where they are set) to the callback thread (where they will be read). Is this possible?
4 Answers
No. You need to keep the context of the operation with the asynchronous call. That's what the "state" parameter is for on most asynchronous calls.
ThreadStatic
variables can be useful in some situations, but I'm generally wary of them. Unless you really know that you don't need any kind of thread agility, it's better to keep the state in a more explicit fashion.

- 1,421,763
- 867
- 9,128
- 9,194
The best approach for this would be to pass your operation some object, one which it can set your threadstatic variable prior to calling back. There is no way to directly access the threadstatic variable from the calling thread.
That being said, I'd rethink your design. If you want the variable to be available from multiple threads, it probably shouldn't be a threadstatic variable. It probably should be managed by some other means.

- 554,122
- 78
- 1,158
- 1,373
If you need to do so, you probably don't want them to be ThreadStatic
. You could make a static Dictionary<int,VarType>
and map thread IDs to variables.

- 414,610
- 91
- 852
- 789
-
Except you generally don't know which thread your async operation is going to be called on. If you can pass around the ID of the "initiating" thread instead, you might as well just pass the whole context instead, and save on the middleman. – Jon Skeet Mar 19 '09 at 19:15
-
Yes, you have to keep track of the appropriate thread IDs in some ways. I don't think this is very useful anyway. I just provided it as workaround instead of accessing thread static vars. I would *not* recommend it as a solution to the higher-level problem. – Mehrdad Afshari Mar 19 '09 at 19:18
It seems to me that the best way would be to use the state parameter, as Jon said. However, if necessary, you could look at System.Runtime.Remoting.Contexts.Context.

- 160,644
- 26
- 247
- 397