Use a manual event object. : ManualResetEvent : Thread C# Examples


C# Examples » Thread » ManualResetEvent »

 

Use a manual event object.









    
using  System;      
using  System.Threading;      
    
class  MyThread  {      
    public  Thread  thrd;    
    ManualResetEvent  manualResetEvent;    
      
    public  MyThread(string  name,  ManualResetEvent  e)  {      
        thrd  =  new  Thread(this.run);      
        thrd.Name  =  name;    
        manualResetEvent  =  e;    
        thrd.Start();      
    }      
      
    void  run()  {      
        Console.WriteLine("Inside  thread  "  +  thrd.Name);    
    
        for(int  i=0;  i<50;  i++)  {    
            Console.WriteLine(thrd.Name);    
            Thread.Sleep(50);    
        }    
    
        Console.WriteLine(thrd.Name  +  "  Done!");    
    
        manualResetEvent.Set();
    }      
}      
      
class  MainClass  {      
    public  static  void  Main()  {      
        ManualResetEvent  evtObj  =  new  ManualResetEvent(false);    
    
        MyThread  myThread  =  new  MyThread("Event  Thread  1",  evtObj);      

        Console.WriteLine("Main  thread  waiting  for  event.");

        //  Wait  for  signaled  event.
        evtObj.WaitOne();

        Console.WriteLine("Main  thread  received  first  event.");

        evtObj.Reset();  

        myThread  =  new  MyThread("Event  Thread  2",  evtObj);      

        //  Wait  for  signaled  event.
        evtObj.WaitOne();

        Console.WriteLine("Main  thread  received  second  event.");

    }      
}
    
   
  
   



Output

Inside thread Event Thread 1
Event Thread 1
Main thread waiting for event.
Event Thread 1
Event Thread 1
Event Thread 1
Event Thread 1
Event Thread 1
Event Thread 1
Event Thread 1
Event Thread 1
^CTerminate batch job (Y/N)? n


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» ManualResetEvent