16th
AUG

.Net: Using ThreadStatic Attribute in Multithreaded Applications

Posted by Sambeet Patra under .NET Software Development

Writing multithreaded programs in .Net requires a good understanding of the threading functionalities available in the .Net Framework. ThreadStatic attribute is a useful keyword in multithreaded programs. As far as functionality is concerned, ThreadStatic attribute is a variation of the static keyword. 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 myVariable;

The program below demonstrates how this attribute changes the behavior of a variable.

using System;
using System.Threading;

class Program
{
public static int timesAccessed = 0;

[ThreadStatic]
public static int timesAccessedInaThread = 0;

static void Main(string[] args)
{
Program myProg = new Program();

//define the threads
Thread thread1 = new Thread(new ThreadStart(myProg.Func1));
Thread thread2 = new Thread(new ThreadStart(myProg.Func2));

//start thread1
thread1.Start();
//wait for thread1 to finish
thread1.Join();

//start thread2
thread2.Start();
//wait for thread2 to finish
thread2.Join();
}

public void Func1()
{
timesAccessed++;
timesAccessedInaThread++;
Console.WriteLine(”value of accessed in Thread1: ” + timesAccessed.ToString());
Console.WriteLine(”value of accessedInaThread in Thread1: ” + timesAccessedInaThread.ToString());
}

public void Func2()
{
timesAccessed++;
timesAccessedInaThread++;
Console.WriteLine(”value of accessed in Thread2: ” + timesAccessed.ToString());
Console.WriteLine(”value of accessedInaThread in Thread2: ” + timesAccessedInaThread.ToString());
}
}
Here timesAccessed is a static variable and timesAccessedInaThread 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.

Leave a Reply