Translate

Tuesday, June 17, 2014

How to make a thread wait for another thread in C# (Signaling C#)

If you need a thread to wait for another thread to complete, then you could use ManualResetEvent Class. What this class does is that it acts as a signal that a thread can use to decide when to proceed.

In the example below, thread 1 waits for a signal from thread 2 to proceed.

using System;
using System.Threading;
 
internal class Signaling
{
    private static ManualResetEvent _signal;
 
    private static void Main()
    {
        _signal = new ManualResetEvent(false);
 
        var thread1 = new Thread(Wait);
        var thread2 = new Thread(CountToTen);
        thread1.Start();
        thread2.Start();
    }
 
    public static void Wait()
    {
        Console.WriteLine("Waiting for a signal");
        _signal.WaitOne(); //Suspend thread until signal is open
        _signal.Dispose();//Once the signal is open, dispose it
        Console.WriteLine("Green Signal! Lets go!");
    }
 
    public static void CountToTen()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
        _signal.Set(); //Open signal
    }
}


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator