C# – AutoResetEvent

Thread Synchronization is basically suspending (making one thread wait) until the other thread meets a certain condition.

Now some of you know the regular Join(), which suspends the calling thread until the called thread meets the condition of finish.

But , I would like to take a look at the Auto Reset Event Class,
which allows synchronization between two threads who’s timings do not align.

There are three basic players in this game:

1. public static AutoResetEvent eventReset = new AutoResetEvent(false) – creates the AutoResetEvent queue instance
2. eventReset.WaitOne() – stops the thread and stacks it into the AutoResetEvent queue by order of arrival.
3. eventReset.Set() – Resumes the first waiting thread in the AutoResetEvent queue.

so how do we use them? we can declare a function and then in the main program start a thread and have it wait until a certain condition is met or lock is passed.

public static void proc() {

// Do some work..
    eventReset.WaitOne();

}
public static AutoResetEvent eventReset = new AutoResetEvent(false);

public static void Main(string[] args) {  

Thread thread = new Thread(proc);
thread.start();



Thread thread2 = new Thread(proc);
thread2.start();

// execution of code... until we call Set() to resume the first suspended thread.

eventReset.Set();  // release first thread...


eventReset.Set(); // release second thread...


}

 

Comments are closed, but trackbacks and pingbacks are open.