线程信号基础知识

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

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

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

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); } } 

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

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

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

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

waitHandle.WaitOne(); 等待信号

waitHandle.Set(); 信号完成。

对我来说,这是一个非常大的区域,可以为您提供明确的指示。

为了理解信令之类的概念, 线程同步上的这个链接将是一个很好的起点。 它也有例子。 然后,您可以根据您尝试执行的操作深入查看特定的.net类型..在进程内的线程之间或跨进程等之间发出信号。