我正在查看本網站的threads。 我一直在玩代碼來回答問題「CountdownEvent是否停止所有線程?」 我得到的答案是否定的。然後我決定玩傳入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線程()來執行,但其他線程執行,同時即使只有四個信號已被調用。
它爲什麼這樣做?
感謝,
dhoehna
爲什麼你會想到其他線程*不*執行?只有你的主線程正在使用'Wait'。其他人只是*信號*倒數。 – 2013-05-13 19:56:31
我期望所有的線程運行並打印一些內容,然後讓程序在CountDown.Wait()調用中永遠阻塞。倒計時的目的是阻止*一個線程*直到其他一些線程發出信號表示繼續安全。 – dlev 2013-05-13 19:57:03
@dlev什麼是錯誤的是,我忘了在所有的線程上等待。我認爲等待是一個全面的陳述。 – 2013-05-14 14:48:12