47 lines
1.0 KiB
Plaintext
47 lines
1.0 KiB
Plaintext
When an object has a field annotated with ``++ThreadStatic++``, that field is shared within a given thread, but unique across threads. Since a class' static initializer is only invoked for the first thread created, it also means that only the first thread will have the expected initial values.
|
|
|
|
|
|
Instead, allow such fields to be initialized to their default values or make the initialization lazy.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
public class Foo
|
|
{
|
|
[ThreadStatic]
|
|
public static object PerThreadObject = new object(); // Noncompliant. Will be null in all the threads except the first one.
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
public class Foo
|
|
{
|
|
[ThreadStatic]
|
|
public static object _perThreadObject;
|
|
public static object PerThreadObject
|
|
{
|
|
get
|
|
{
|
|
if (_perThreadObject == null)
|
|
{
|
|
_perThreadObject = new object();
|
|
}
|
|
return _perThreadObject;
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|