Threading in dot net 2.0 – separate copy of static variable among different threads using ThreadStatic attribute

Google+ Pinterest LinkedIn Tumblr +

Windows basic unit of execution is a thread. That means WIN does not execute processes; instead, it executes threads. Threads are code sequences that run multitasked on individual stacks. A thread has its own sequence of code, which gets executed in a concurrent fashion. So threads help us achieve concurrent processing. WIN Scheduler controls the execution of all the threads running in a system. In WIN, each thread has its own priority, numbered from 0 to 31, based on which WIN schedules the execution of each thread. The higher the priority number, the higher the thread’s priority. A process may have a single thread or multiple threads. A single process has to have a minimum of one thread. Processes can spawn threads and can terminate threads.

Below Program shows how each thread keeps a separate copy of same static variable using ThreadStatic attribute

using System ;

using System.Collections.Generic ;

using System.Text ;

using System.Threading ;

namespace Thread_Programming

{

class ThreadStaticProgram

{

[ThreadStatic]

static string threadStaticVariable = “” ;

static void Main( string[] args )

{

Console.WriteLine(” Main Thread Before {0} “, threadStaticVariable ) ;

threadStaticVariable = ” Main Thread “;

Console.WriteLine(” Main Thread Before For Loop = {0} ” , threadStaticVariable ) ;

Thread[] threads = new Thread[3];

for ( int i = 0; i < 3; i++ )

{

threads[i]= new Thread( delegate( object j ) {

Console.WriteLine( ” Thread{0} before = {1} “, j , threadStaticVariable );

threadStaticVariable = ” Thread ” + j;

Console.WriteLine( ” Thread{0} after ={1} ” ,j , threadStaticVariable );

}

) ;

threads[i].Start( i ) ;

}

Array.ForEach( threads , delegate( Thread t ) { t.Join() ; } ) ;

Console.WriteLine( ” Main Thread after For Loop = {0} “, threadStaticVariable ) ;

Console.ReadLine();

}

}

}

Result on Console Screen :

Main Thread Before

Main Thread Before For Loop = Main Thread

Thread0 before =

Thread1 before =

Thread1 after = Thread1

Thread0 after = Thread0

Thread2 before =

Thread2 after = Thread2

Main Thread after For Loop = Main Thread

Share.

About Author

Leave A Reply