# V3089. Initializer of a field marked by [ThreadStatic] attribute will be called once on the first accessing thread. The field will have default value on different threads.

The analyzer detected a suspicious code fragment where a field marked with the '[ThreadStatic]' attribute is initialized at declaration or in a static constructor.

If the field is initialized at declaration, it will be initialized to this value only in the first accessing thread. In every next thread, the field will be set to the default value.

A similar situation is observed when initializing the field in a static constructor: the constructor executes only once, and the field will be initialized only in the thread where the static constructor executes.

Consider the following example, which deals with field initialization at declaration:

    class SomeClass
    {
      [ThreadStatic]
      public static Int32 field = 42;
    }

    class EntryPoint
    {
      static void Main(string[] args)
      {
        new Task(() => { var a = SomeClass.field; }).Start(); // a == 42
        new Task(() => { var a = SomeClass.field; }).Start(); // a == 0
        new Task(() => { var a = SomeClass.field; }).Start(); // a == 0
      }
    }

When the first thread accesses the 'field' field, the latter will be initialized to the value specified by the programmer. That is, the 'a' variable, as well as the 'field' field, will be set to the value '42'.

From that moment on, as new threads start and access the field, it will be initialized to the default value ('0' in this case), so the 'a' variable will be set to '0' in all the subsequent threads.

As mentioned earlier, initializing the field in a static constructor does not solve the problem, as the constructor will be called only once (when initializing the type), so the problem remains.

It can be dealt with by wrapping the field in a property with additional field initialization logic. It helps solve the problem, but only partially: when the field is accessed instead of the property (for example inside a class), there is still a risk of getting an incorrect value.

    class SomeClass
    {
      [ThreadStatic]
      private static Int32 field = 42;

      public static Int32 Prop
      {
        get
        {
          if (field == default(Int32))
            field = 42;

          return field;
        }

        set
        {
          field = value;
        }
      }
    }
    class EntryPoint
    {
      static void Main(string[] args)
      {
        new Task(() => { var a = SomeClass.Prop; }).Start(); // a == 42
        new Task(() => { var a = SomeClass.Prop; }).Start(); // a == 42
        new Task(() => { var a = SomeClass.Prop; }).Start(); // a == 42
      }
    }

This diagnostic is classified as:

CWE-665

You can look at examples of errors detected by the V3089 diagnostic.