[ThreadStatic] is defined using attribute while ThreadLocal uses generic.
Why different design solutions were chosen?
What are the advan
The main idea behind ThreadStatic is to maintain a separate copy of the variable for each thread.
class Program
{
[ThreadStatic]
static int value = 10;
static void Main(string[] args)
{
value = 25;
Task t1 = Task.Run(() =>
{
value++;
Console.WriteLine("T1: " + value);
});
Task t2 = Task.Run(() =>
{
value++;
Console.WriteLine("T2: " + value);
});
Task t3 = Task.Run(() =>
{
value++;
Console.WriteLine("T3: " + value);
});
Console.WriteLine("Main Thread : " + value);
Task.WaitAll(t1, t2, t3);
Console.ReadKey();
}
}
In the above snippet, we have a separate copy of value for each thread, including the main thread.
So, a ThreadStatic variable will be initialized to its default value on other threads except the thread on which it is created.
If we want to initialize the variable on each thread in our own way, use ThreadLocal.