Sometimes when working with .NET you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is the ThreadLocal class.
For a long time I’m using the [ThreadStatic] attribute in .NET. It allows you in an easy way to create static variables scoped on a per thread basis. Using it is easy, it is simply a matter of decorating a static field with the [ThreadStatic]
attribute:
As mentioned by Jon Skeet, using ThreadStatic has some disadvantages:
- The variable must be static
- You have to call the initialization logic yourself
- Limited PCL support
.NET 4.5 introduces another class that solves the same problem: ThreadLocal.
It offers the same functionality as the ThreadStatic attribute but does not have its disadvantages:
- The variable doesn’t have to be static
- You can specify an initialization delegate to be executed on first use in any particular thread (similar in the way you initialize Lazy<T>)
- The intent is more clear