Why Initializing threadstatic attribute in Threadlocal delegate doesn't initilize it for the first thread?

383 Views Asked by At

I have created 3 threads and all threads have operation of increament on threadlocal attribute except thread1. I am also initializing threadstatic attribute in threadlocal delegate by the value of 11. Here I always get the value of num = 0 in the first thread. Why so?

class Program
    {
        //static int numDuplicate = 0;
        [ThreadStatic]
        static int num = 5;

        public static ThreadLocal<int> _field = new ThreadLocal<int>(() =>
        {
            num = 11;
            //numDuplicate = num;
            Console.WriteLine("Threadstatic variable value in Threadlocal's delegate = " + num.ToString());
            return Thread.CurrentThread.ManagedThreadId;
        });



        public static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(() =>
            {
                Console.WriteLine("Threadlocal attribute value for thread 1: " + _field + ". Threadstatic variable value = " + num.ToString());
            }));

            Thread t2 = new Thread(new ThreadStart(() =>
            {
                _field.Value++;
            Console.WriteLine("Threadlocal attribute value for thread 2: " + _field + ". Threadstatic variable value = " + num.ToString());
            }));

            Thread t3 = new Thread(new ThreadStart(() =>
            {
                _field.Value++;
                Console.WriteLine("Threadlocal attribute value for thread 3: " + _field + ". Threadstatic variable value = " + num.ToString());
            }));

            t1.Start();
            t2.Start();
            t3.Start();
            Console.ReadLine();
        }
    }

//Output:
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadlocal attribute value for thread 1: 10. Threadstatic variable value = 0
Threadlocal attribute value for thread 3: 13. Threadstatic variable value = 11
Threadlocal attribute value for thread 2: 12. Threadstatic variable value = 11
1

There are 1 best solutions below

0
On

Because 'cannot' assign an initial value for ThreadStatics.

Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value if it is a value type, or to null if it is a reference type.

Source: MSDN


You might take a look at ThreadLocal<>

static ThreadLocal<int> num  = new ThreadLocal<int>(() => 5);

The Func<> will be executed as initialization foreach new thread. In this case it just returns 5.