Cause
A field that's annotated with System.ThreadStaticAttribute is initialized inline or explicitly in a static (Shared in Visual Basic) constructor.
Rule description
System.ThreadStaticAttribute fields should be initialized lazily on use and not with inline initialization or explicitly in a static (Shared in Visual Basic) constructor. A static constructor only initializes the field on the thread that runs the type's static constructor.
How to fix a violation
To fix a violation, remove the inline or static constructor initialization. Instead, initialize the field on first use.
Example
The following code snippet shows a violation of CA2019:
class C
{
[ThreadStatic]
private static Object obj = new();
}Class C
<ThreadStatic>
Private Shared obj As New Object()
End ClassThe following code snippet shows how to fix a violation:
class C
{
[ThreadStatic]
private static Object obj;
static void S1()
{
obj ??= new Object();
}
}Class C
<ThreadStatic>
Private Shared obj
Shared Sub S1()
If obj Is Nothing Then
obj = New Object()
End If
End Sub
End ClassWhen to suppress warnings
It's safe to suppress a warning from this rule, but your app might exhibit unexpected behavior.