Code Inspection: Thread static field has initializer
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;
}
}
<ThreadStatic>
Private Shared Dim myFoo As Object
Public Shared ReadOnly Property Foo As Object
Get
If (myFoo Is Nothing) Then myFoo = New Object()
Return myFoo
End Get
End Property
Alternatively, the ThreadLocal<>
class can be used (as of .NET 4.0):
private ThreadLocal<object> myFoo = new ThreadLocal<object>(() => new object());
Dim myFoo As ThreadLocal(Of Object) = new ThreadLocal(Of Object)(Function() New Object())
Last modified: 21 March 2024