Search code examples
c#.netmultithreading.net-4.0clr

ThreadLocal<T> and static approach?


Static fields are being accessed using the class name like this:

public class Me()
{ 
  public static int a=5;
}

I can access it with Me.a, so it is attached to the class.

But when I look at:

static ThreadLocal<int> _x = new ThreadLocal<int> (() => 3);

It guarantees that each thread sees different copy of _x.

Didn't we just see that static is per class and not per thread? How does ThreadLocal manage to give each thread a different copy of _x?


Solution

  • 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.