How does [ThreadStatic] attribute work? I assumed that the compiler would emit some IL to stuff/retrieve the value in the TLS, but looking at a disassembly it d
The [ThreadStatic] creates isolated versions of the same variable in each thread.
Example:
[ThreadStatic] public static int i; // Declaration of the variable i with ThreadStatic Attribute.
public static void Main()
{
new Thread(() =>
{
for (int x = 0; x < 10; x++)
{
i++;
Console.WriteLine("Thread A: {0}", i); // Uses one instance of the i variable.
}
}).Start();
new Thread(() =>
{
for (int x = 0; x < 10; x++)
{
i++;
Console.WriteLine("Thread B: {0}", i); // Uses another instance of the i variable.
}
}).Start();
}