Thread Static field : Static Thread Field : Thread C# Examples


C# Examples » Thread » Static Thread Field »

 

Thread Static field









    
using  System;
using  System.Threading;

public  class  Task  {
  
    [ThreadStatic]  
    static  int  id  =  10;

    public  string    threadName;
    
    public  void  Run(  string  ThreadName  )  {
        this.threadName  =  ThreadName;
        Thread  T  =  new  Thread(  new  ThreadStart(  process  )  );
        T.Start(  );
    }

    public  void  process(  )  {
        Console.WriteLine(  "Thread  {0}  is  running",  threadName  );

        for(int  i  =  0;  i  <  10;  i++  )
            Console.WriteLine("Thread  {0}  :  id  =  {1}",  this.threadName,  id++  );
    }
}


public  class  MainClass  {

    public  static  void  Main(  )  {
        Task  t1  =  new  Task(  );
        Task  t2  =  new  Task(  );

        t1.Run(  "Worker  1"  );
        t2.Run(  "Worker  2"  );
        
        Task  t3  =  new  Task(  );
        t3.threadName  =  "Main  Thread";
        t3.process(  );
    }
}
    
   
  
   



Output

Thread Worker 1 is running
Thread Worker 1 : id = 0
Thread Worker 1 : id = 1
Thread Worker 1 : id = 2
Thread Worker 1 : id = 3
Thread Worker 1 : id = 4
Thread Worker 1 : id = 5
Thread Worker 1 : id = 6
Thread Worker 1 : id = 7
Thread Worker 1 : id = 8
Thread Worker 1 : id = 9
Thread Worker 2 is running
Thread Worker 2 : id = 0
Thread Worker 2 : id = 1
Thread Worker 2 : id = 2
Thread Worker 2 : id = 3
Thread Worker 2 : id = 4
Thread Worker 2 : id = 5
Thread Worker 2 : id = 6
Thread Worker 2 : id = 7
Thread Worker 2 : id = 8
Thread Worker 2 : id = 9
Thread Main Thread is running
Thread Main Thread : id = 10
Thread Main Thread : id = 11
Thread Main Thread : id = 12
Thread Main Thread : id = 13
Thread Main Thread : id = 14
Thread Main Thread : id = 15
Thread Main Thread : id = 16
Thread Main Thread : id = 17
Thread Main Thread : id = 18
Thread Main Thread : id = 19


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Static Thread Field