Using ThreadStaticAttribute

 Rate It (0)

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.

Revision number 2, Tuesday, August 26, 2008 6:53:09 PM by sambeetpatra

Comments

gud article on a confusing thing

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter