ThreadLocal<T> and static approach?

Didnt we just see that static is per class and not per thread ?

Yes. So imagine that a ThreadLocal<T> instance holds a static Dictionary<Thread, T> that looks up the Value for the current thread.

That is probably not how it actually works but it's a simple explanation of how it's possible. You could write it yourself.

So you still have only 1 static _x. But _x.Value can be bound to anything, like the courrent Thread.


The reference _x will indeed be one per class, as per its static specifier. However, only the reference will be shared among all threads, not the value inside its object. When you access _x.Value, ThreadLocal<T> invokes system-specific code that provides storage on the current thread, and reads or writes to that thread-specific storage.


My C# isn't that great, so here's a C++ answer to the same effect: Imagine a hypothetical class that contains a large array:

class Foo
{
    int array[HUGE];
    int & get() { return array[this_thread_id()]; }
}:

Now you can have one single, global (or class-static) object:

Foo tlstorage;

To access it from anywhere you say tlstorage.get() = 12;. However, the data is stored in the slot that "belongs" to your current thread. The entire storage is global, but only one slice is exposed to each thread.

Other languages like C and C++ have native support for this concept, and when you decorate a global or static variable as "thread-local", the compiler builds something that amounts to the same effect automatically. Perhaps in C# this is a library feature, though it probably also maps to something intrinsic.