This is an attribute that indicates that the variable has one instance for each thread. This is a variation of the static variables. Static variables have one instance throughout the lifecycle of the program. A variable marked with [ThreadStatic] has one instance per thread in the program.
The syntax is shown below in C#
[ThreadStatic]
static int someValue;
To better understand this key, let us consider the following program
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
public static int accessed = 0;
[ThreadStatic]
public static int accessedInaThread = 0; //we want this variable to be considered static per thread
static void Main(string[] args)
{
Program prog = new Program();
//define the threads
Thread thread1 = new Thread(new ThreadStart(prog.ThreadFunc1));
Thread thread2 = new Thread(new ThreadStart(prog.ThreadFunc2));
//start thread1
thread1.Start();
//wait for thread1 to finish
thread1.Join();
//start thread2
thread2.Start();
//wait for thread2 to finish
thread2.Join();
}
public void ThreadFunc1()
{
accessed++;
accessedInaThread++;
Console.WriteLine("value of accessed in Thread1: " + accessed.ToString());
Console.WriteLine("value of accessedInaThread in Thread1: " + accessedInaThread.ToString());
}
public void ThreadFunc2()
{
accessed++;
accessedInaThread++;
Console.WriteLine("value of accessed in Thread2: " + accessed.ToString());
Console.WriteLine("value of accessedInaThread in Thread2: " + accessedInaThread.ToString());
}
}
}
Here accessed is a static variable and accessedInaThread is a ThreadStatic variable. These variables are accessed and changed in two different threads. Note the output of the program:
value of accessed in Thread1: 1
value of accessedInaThread in Thread1: 1
value of accessed in Thread2: 2
value of accessedInaThread in Thread2: 1
Here the threadstatic variable has a different copy for each thread. Hence, the change in value in thread1 does not impact the value in thread2.
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.