线程信号基础知识

Mar*_*ote 13 c# multithreading

我知道C#,但我很难理解一些基本的(我认为)概念,比如信号.

我花了一些时间寻找一些例子,即使在这里也没有运气.也许一些例子或一个真实的简单场景会很好理解它.

Amr*_*mry 24

这是一个定制的控制台应用程序示例.实际上并不是一个好的现实场景,但线程信令的使用是存在的.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

简而言之,这种方式起作用.

  1. AutoResetEvent waitHandle = new AutoResetEvent(false); --- false表示如果调用waitHandle.WaitOne(),那么等待句柄是无信号的,它将停止该线程.

  2. 您要等待另一个事件完成添加的线程 waitHandle.WaitOne();

  3. 在需要完成的线程中,在完成添加时结束 waitHandle.Set();

waitHandle.WaitOne(); 等待信号

waitHandle.Set(); 信号完成.