23

In C# how does one achieve thread signaling?

3 Answers 3

38

Here is a custom-made console application example for you. Not really a good real world scenario, but the usage of thread signaling is there.

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        bool isCompleted = false;
        int diceRollResult = 0;

        // AutoResetEvent is one type of the WaitHandle that you can use for signaling purpose.
        AutoResetEvent waitHandle = new AutoResetEvent(false);

        Thread thread = new Thread(delegate() {
            Random random = new Random();
            int numberOfTimesToLoop = random.Next(1, 10);

            for (int i = 0; i < numberOfTimesToLoop - 1; i++) {
                diceRollResult = random.Next(1, 6);

                // Signal the waiting thread so that it knows the result is ready.
                waitHandle.Set();

                // Sleep so that the waiting thread have enough time to get the result properly - no race condition.
                Thread.Sleep(1000);
            }

            diceRollResult = random.Next(1, 6);
            isCompleted = true;

            // Signal the waiting thread so that it knows the result is ready.
            waitHandle.Set();
        });

        thread.Start();

        while (!isCompleted) {
            // Wait for signal from the dice rolling thread.
            waitHandle.WaitOne();
            Console.WriteLine("Dice roll result: {0}", diceRollResult);
        }

        Console.Write("Dice roll completed. Press any key to quit...");
        Console.ReadKey(true);
    }
}
0
14

The way this works in a nutshell.

  1. AutoResetEvent waitHandle = new AutoResetEvent(false); --- The false means that that wait handle is unsignaled if a waitHandle.WaitOne() is called it will stop the thread.

  2. The thread you want to wait for another event to complete add waitHandle.WaitOne();

  3. In the thread that needs to be completed,at the end when completed add waitHandle.Set();

waitHandle.WaitOne(); Waits for signal

waitHandle.Set(); signals completion.

1
  • 1
    At last some clarity. From reading other posts I got the wrong impression that I had to use set and reset. Still lots of stupid socket errors but your post has helped me to make some progress. Thank you. Commented Jun 7, 2020 at 0:55
4

For understanding concepts like signaling, see Thread Synchronization which would be a good place to start.

It's got examples too. You can then drill down into specific .net types based on what you're trying to do.. signal between threads within a process or across processes etc..

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.