Code Inspection: [ThreadStatic] doesn't work with instance fields
Last modified: 08 March 2021
tip
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());