螺纹基础的信令 [英] Thread signaling basics
本文介绍了螺纹基础的信令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道C#,但我总对新手线程和我无法理解像信令一些基本的(我认为)的概念。
我花了一些时间寻找一些例子,即使在这里,没有运气。
也许一些例子或一个真正简单的场景将是巨大的去了解它。
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.
感谢很多提前。
推荐答案
下面是为您定制的控制台应用实例。 。不是一个真正的好真实世界的场景,但信号线的使用是有
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);
}
}
这篇关于螺纹基础的信令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文