我在这个网站上寻找 threads . 我一直在玩代码来回答“CountdownEvent 是否停止所有线程?”这个问题。 我得到的答案是否定的。然后我决定使用传递给 CountdownEvent 的数字。这是我的代码
namespace ThreadPractice
{
class Program
{
static CountdownEvent CountDown = new CountdownEvent(4);
static void Main()
{
new Thread(() => SaySomething("I am Thread one.")).Start();
new Thread(() => SaySomething("I am thread two.")).Start();
new Thread(() => SaySomethingElse("Hello From a different Thread")).Start();
new Thread(() => SaySomething("I am Thread Three.")).Start();
CountDown.Wait();
Console.Read();
}
static void SaySomething(string Something)
{
Thread.Sleep(1000);
Console.WriteLine(Something);
CountDown.Signal();
}
static void SaySomethingElse(string SomethingElse)
{
Thread.Sleep(1000);
Console.WriteLine(SomethingElse);
}
}
}
我期望调用 SaySomethingELse() 的线程执行,但其他线程也执行,即使只调用了四个信号。
为什么要这样做?
谢谢,
多哈
最佳答案
在我看来,您的 Signal
和 Wait
方向不对。如果您希望 SaySomething
调用等待倒计时达到 0,您应该调用 Wait
。这是一个例子:
using System;
using System.Threading;
namespace ThreadPractice
{
class Program
{
static CountdownEvent CountDown = new CountdownEvent(4);
static void Main()
{
new Thread(() => SaySomething("I am Thread one.")).Start();
new Thread(() => SaySomething("I am thread two.")).Start();
new Thread(() => SaySomethingElse("Hello From a different Thread")).Start();
new Thread(() => SaySomething("I am Thread Three.")).Start();
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Calling Signal (time #{0})", i);
CountDown.Signal();
Thread.Sleep(1000);
}
Console.WriteLine("Done");
}
static void SaySomething(string Something)
{
CountDown.Wait();
Console.WriteLine(Something);
}
static void SaySomethingElse(string SomethingElse)
{
Thread.Sleep(1000);
Console.WriteLine(SomethingElse);
}
}
}
输出:
Calling Signal (time #0)
Hello From a different Thread
Calling Signal (time #1)
Calling Signal (time #2)
Calling Signal (time #3)
I am Thread one.
I am Thread Three.
I am thread two.
Done
关于c# - CountDownEvent 不会等到所有信号都被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530058/