Tuesday, September 9, 2008

ThreadStatic Attribute

The [ThreadStatic]attribute 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.

See the example for more details.
class Program
{
public static Int32 singleton = 0;
[ThreadStatic]
public static Int32 threadSingleton = 0;
static void Main(string[] args)
{
Program executingProgram = new Program();
Thread firstThread = new Thread(new ThreadStart(executingProgram.FirstThread));
Thread secondThread = new Thread(new ThreadStart(executingProgram.SecondThread));
firstThread.Start();
firstThread.Join();
secondThread.Start();
firstThread.Join();
Console.Read();
}

public void FirstThread()
{
singleton++;
threadSingleton++;
Console.WriteLine("Singleton = {0} ThreadSingleton = {1}", singleton.ToString(), threadSingleton.ToString());
}

public void SecondThread()
{
singleton++;
threadSingleton++;
Console.WriteLine("Singleton = {0} ThreadSingleton = {1}", singleton.ToString(), threadSingleton.ToString());
}
}

Output
Singleton = 1 ThreadSingleton = 1
Singleton = 2 ThreadSingleton = 1

4 comments:

Anonymous said...

Looks like there is an error in the code, in the main function you have:
firstThread.Join();
secondThread.Start();
firstThread.Join();

To me it looks like the second .Join() should be on secondThread, not firstThread as firstThread will always be complete at that stage.

Visharad said...

No Issues with Code. :) Thanks for the explanation

Visharad said...

No issue with code. It worked well Thanks :)

Visharad said...

No issue with code. It worked well Thanks :)