[英]c# Thread sync - AutoResetEvent
我一直在使用AutoResetEvent在線程之間進行同步。
但是,只有一個等待線程(AF)被解除阻塞。 - 當線程(X)完成它的工作時,我怎樣才能讓它們全部解鎖?
我想我使用了錯誤的同步原語 - 我應該使用什么以及如何使用?
代碼樣本將是理想的
假設你有這個代碼:
class Program
{
static void Main(string[] args)
{
var are = new AutoResetEvent(false);
for (int i = 0; i < 10; i++)
{
var j = i;
new Thread(() =>
{
Console.WriteLine("Started {0}", j);
are.WaitOne();
Console.WriteLine("Continued {0}", j);
}).Start();
}
are.Set();
Console.ReadLine();
}
}
然后你會得到這樣的輸出:
Started 0
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Continued 0
Started 9
但是如果您改為使用ManualResetEvent
:
class Program
{
static void Main(string[] args)
{
var mre = new ManualResetEvent(false);
for (int i = 0; i < 10; i++)
{
var j = i;
new Thread(() =>
{
Console.WriteLine("Started {0}", j);
mre.WaitOne();
Console.WriteLine("Continued {0}", j);
}).Start();
}
mre.Set();
Console.ReadLine();
}
}
然后你會得到我猜的預期行為:
Started 0
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Started 9
Continued 1
Continued 8
Continued 7
Continued 4
Continued 5
Continued 6
Continued 3
Continued 0
Continued 9
Continued 2
當然,顧名思義,需要手動重置ManualResetEvent
,而在第一個WaitOne
釋放其線程后, AutoResetEvent
自動重置。
使用System.Threading.ManualResetEvent。
線程AF調用mre.WaitOne()
在線程(X)上等待。
當線程X完成時,調用mre.Set()
將喚醒線程AF。
在線程X中,通過執行mre.Reset()
重置為基本狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.