skb
skb

Reputation: 31164

Thread Static variables for asynchronous operations in .NET

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?

Upvotes: 2

Views: 1138

Answers (4)

John Saunders
John Saunders

Reputation: 161831

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.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422252

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503459

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.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564851

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.

Upvotes: 1

Related Questions