Edit

Share via


CA2019: ThreadStatic fields should not use inline initialization

Property Value
Rule ID CA2019
Title ThreadStatic fields should not use inline initialization
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

A field that's annotated with ThreadStaticAttribute is initialized inline or explicitly in a static (Shared in Visual Basic) constructor.

Rule description

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 Class

The 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 Class

When to suppress warnings

It's safe to suppress a warning from this rule, but your app might exhibit unexpected behavior.

See also