ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Thread static field has initializer

Last modified: 11 February 2024

The ThreadStaticAttribute makes a field thread-local. This means that every thread has its own reference corresponding to the field. Fields marked with ThreadStaticAttribute must be static and not initialized statically.

This attribute does not affect instance fields. If you need a thread-local instance field you can use the ThreadLocal<> type that has been introduced in .NET 4.0.

If a static field has an initializer, this initializer is invoked only once - on the thread that executes the static constructor. If initialization on all threads is needed, then the field can be encapsulated by a lazy-initialized property:

[ThreadStatic]
private static object myFoo;
public static object Foo
{
  get
  {
    if (myFoo == null)
      myFoo = new object();
    return myFoo;
  }
}

Alternatively, the ThreadLocal<> class can be used (as of .NET 4.0):

private ThreadLocal<object> myFoo = new ThreadLocal<object>(() => new object());