views:

490

answers:

4

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?

+1  A: 

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.

Reed Copsey
+2  A: 

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.

Jon Skeet
A: 

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.

Mehrdad Afshari
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
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
A: 

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.

John Saunders