.NET 4.0 provides a thread local storage, simply by adding a field of type ThreadLocal<T>. The field will have a different instance for each thread! Have a look at the following sample:
public class ThreadLocalSample
{
static ThreadLocal<int> count = new ThreadLocal<int>(() => 10);
public ThreadLocalSample()
{
new Thread(minus).Start();
for (int i = 0; i < short.MaxValue; i++)
{
count.Value++;
}
Console.WriteLine("Add: Local Thread Variable = {0}", count.Value);
}
private void minus()
{
for (int i = 0; i < short.MaxValue; i++)
{
count.Value--;
}
Console.WriteLine("Minus: Local Thread Variable = {0}", count.Value);
}
}
The feature also exits before version .NET 4.0, you simply have to decorate a static field with ThreadStaticAttribute. It has the same effect than using ThreadLocal<T>!
ThreadStaticAttribute does [b]not[/b] have the same effect as ThreadLocal<T>: ThreadStaticAttribute has no effect on instance fields, it only works on static fields. But you can have instance fields of type ThreadLocal<T>, it works as expected (i.e. the value is local per instance AND per thread, which you can’t achieve with ThreadStaticAttribute)