In multithreaded programming, we often want to create a variable that is local to a thread, which means that each thread will have its own copy of the data. This holds true for all local variables, but global variables are always shared across threads. In old versions of .NET, we used the ThreadStatic attribute to make a static variable behave as a thread-local variable. However, this is not foolproof and doesn't work well with initialization. If we are initializing a ThreadStatic variable, then only the first thread gets the initialized value, whereas the rest of the threads get the default value of the variable, which is 0 in the case of an integer. This can be demonstrated using the following code:
[ThreadStatic]
static int counter = 1;
public static void Main()
{
for (int i = 0; i < 10; i++)
{
Task.Factory...