Create a thread of execution : Thread Creation : Thread C# Examples


C# Examples » Thread » Thread Creation »

 

Create a thread of execution









    
using  System;  
using  System.Threading;  
  
class  MyThread  {  
    public  int  count;  
    string  thrdName;  
  
    public  MyThread(string  name)  {  
        count  =  0;  
        thrdName  =  name;  
    }  
  
    //  Entry  point  of  thread.  
    public  void  run()  {  
        Console.WriteLine(thrdName  +  "  starting.");  
  
        do  {  
            Thread.Sleep(500);  
            Console.WriteLine("In  "  +  thrdName  +  
                                                ",  count  is  "  +  count);  
            count++;  
        }  while(count  <  10);  
  
        Console.WriteLine(thrdName  +  "  terminating.");  
    }  
}  
  
class  MainClass  {  
    public  static  void  Main()  {  
        Console.WriteLine("Main  thread  starting.");  
  
        MyThread  mt  =  new  MyThread("Child  #1");  
        Thread  newThrd  =  new  Thread(new  ThreadStart(mt.run));  
  
        newThrd.Start();  
  
        do  {  
            Console.Write(".");  
            Thread.Sleep(100);  
        }  while  (mt.count  !=  10);  
  
        Console.WriteLine("Main  thread  ending.");  
    }  
}
    
   
  
   



Output

Main thread starting.
Child #1 starting.
.....In Child #1, count is 0
.....In Child #1, count is 1
....In Child #1, count is 2
.....In Child #1, count is 3
....In Child #1, count is 4
.....In Child #1, count is 5
.....In Child #1, count is 6
....In Child #1, count is 7
.....In Child #1, count is 8
....In Child #1, count is 9
Child #1 terminating.
Main thread ending.


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Thread Creation