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.
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.
To fix a violation, remove the inline or static
constructor initialization. Instead, initialize the field on first use.
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 alsoRetroSearch 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