views:

54

answers:

2

Hello!

I know C# , but I am a total newbie regarding threading and I am having trouble to understand some basic (I think) concepts like signaling. I spent some time looking for some examples, even here, without luck. Maybe some examples or a real simple scenario would be great to understand it.

Thanks a lot in advance.

A: 

It's a pretty large area for me to give you definite pointers.

For understanding concepts like signaling, this link on Thread Synchronization 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..

Gishu
+1  A: 

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);
    }
}
Amry
Thanks and sorry for the late response Amry (video card died yesterday, bought new one today). I'll run it right away.
Markust