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


C# Examples » Thread » Static Thread Field »

 

Static Thread field









    
using  System;
using  System.Threading;

public  class  MyClass
{
        public  MyClass()  {
                Console.WriteLine(  "Creating  MyClass"  );
        }
}

public  class  MyStaticThreadClass
{
        [ThreadStatic]
        public  static  MyClass  tlsdata  =  new  MyClass();
}

public  class  MainClass
{
        private  static  void  ThreadFunc()  {
                Console.WriteLine(  "Thread  {0}  starting...",  Thread.CurrentThread.GetHashCode()  );
                Console.WriteLine(  "tlsdata  for  this  thread  is  \"{0}\"",  MyStaticThreadClass.tlsdata  );
                Console.WriteLine(  "Thread  {0}  exiting",  Thread.CurrentThread.GetHashCode()  );
        }

        static  void  Main()  {
                Thread  thread1  =  new  Thread(  new  ThreadStart(ThreadFunc)  );
                Thread  thread2  =  new  Thread(  new  ThreadStart(ThreadFunc)  );

                thread1.Start();
                thread2.Start();
        }
}
    
   
  
   



Output

Thread 3 starting...
Creating MyClass
tlsdata for this thread is "MyClass"
Thread 3 exiting
Thread 4 starting...
tlsdata for this thread is ""
Thread 4 exiting


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Static Thread Field