Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ThreadStatic value of another thread?

Is it possible given the Thread reference to get ThreadStatic value for that thread?

like image 704
Poma Avatar asked Feb 19 '15 11:02

Poma


1 Answers

No, that's not possible. As common with attributes like this one, the [ThreadStatic] attribute is recognized by the jitter. It generates a call into the CLR to obtain a pointer to the thread-local storage for a class. There are multiple versions of this helper method, the basic one is JIT_GetSharedGCThreadStaticBase(). But it gets more convoluted for a generic class for example, it can have multiple static variables based on the type parameter. The helper function takes two non-obvious arguments, the module ID and the class ID. Those IDs depend on the AppDomain in which the code was loaded.

Long story short, you don't stand a chance to make this same call, nor does the helper method even take the thread ID, it is implied by the call context.

You can hang arbitrary data off a thread with Thread.AllocateNamedDataSlot(). But note that it is static method and doesn't take a thread ID either, it is again based on the call context.

This is all quite intentional. A very nice property of thread-local storage is that it is always thread-safe. A backdoor that would permit accessing it from another thread would completely destroy that feature. Something that should worry you a great deal if you want to do this. You could, with, say, your own lookup table that's keyed by the ManagedThreadId.

like image 56
Hans Passant Avatar answered Oct 17 '22 03:10

Hans Passant