For a long time I was using the ThreadStatic attribute to make the value of a static or instance field local to a thread (i.e. each thread holds an independent copy of the field). Although this did the trick for a long time, the ThreadStatic attribute had some disadvantages:
- the ThreadStatic attribute doesn’t work with instance fields, it compiles and runs but does nothing..
- fields always start with the default value
With the release of C# 4 Microsoft introduced a new class specifically for the thread-local storage of data – the ThreadLocal<T> class:
2: ThreadLocal<int> _localField = new ThreadLocal<int>(() => 1);
So why should you choose the ThreadLocal<T> class?
- Thanks to the use of a factory function, the values are lazily evaluated, the factory function only executes on the first call for each thread
- you have more control over the initialization of the field and you are able to initialize the field with a non-default value