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
Because 'cannot' assign an initial value for ThreadStatics.
Source: MSDN
You might take a look at
ThreadLocal<>
The
Func<>
will be executed as initialization foreach new thread. In this case it just returns 5.