A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2019 below:

CA2019: 'ThreadStatic' fields should not use inline initialization - .NET

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4