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;
}
}
}