原文鏈接:http://dotnetpattern.com/threading-autoresetevent
AutoResetEvent是.net線程簡易同步方法中的一種。
AutoResetEvent 常常被用來在兩個線程之間進行信號發送
兩個線程共享相同的AutoResetEvent對象,線程可以通過調用AutoResetEvent對象的WaitOne()方法進入等待狀態,然后另外一個線程通過調用AutoResetEvent對象的Set()方法取消等待的狀態。
AutoResetEvent如何工作的
在內存中保持着一個bool值,如果bool值為False,則使線程阻塞,反之,如果bool值為True,則使線程退出阻塞。當我們創建AutoResetEvent對象的實例時,我們在函數構造中傳遞默認的bool值,以下是實例化AutoResetEvent的例子。
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
WaitOne 方法
該方法阻止當前線程繼續執行,並使線程進入等待狀態以獲取其他線程發送的信號。WaitOne將當前線程置於一個休眠的線程狀態。WaitOne方法收到信號后將返回True,否則將返回False。
autoResetEvent.WaitOne();
WaitOne方法的第二個重載版本是等待指定的秒數。如果在指定的秒數后,沒有收到任何信號,那么后續代碼將繼續執行。
static void ThreadMethod() { while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2))) { Console.WriteLine("Continue"); Thread.Sleep(TimeSpan.FromSeconds(1)); } Console.WriteLine("Thread got signal"); }
這里我們傳遞了2秒鍾作為WaitOne方法的參數。在While循環中,autoResetEvent對象等待2秒,然后繼續執行。當線程取得信號,WaitOne返回為True,然后退出循環,打印"Thread got signal"的消息。
Set 方法
AutoResetEvent Set方法發送信號到等待線程以繼續其工作,以下是調用該方法的格式。
autoResetEvent.Set();
AutoResetEvent例子
下面的例子展示了如何使用AutoResetEvent來釋放線程。在Main方法中,我們用Task Factory創建了一個線程,它調用了GetDataFromServer方法。調用該方法后,我們調用AutoResetEvent的WaitOne方法將主線程變為等待狀態。在調用GetDataFromServer方法時,我們調用了AutoResetEvent對象的Set方法,它釋放了主線程,並控制台打印輸出dataFromServer方法返回的數據。
class Program { static AutoResetEvent autoResetEvent = new AutoResetEvent(false); static string dataFromServer = ""; static void Main(string[] args) { Task task = Task.Factory.StartNew(() => { GetDataFromServer(); }); //Put the current thread into waiting state until it receives the signal autoResetEvent.WaitOne(); //Thread got the signal Console.WriteLine(dataFromServer); } static void GetDataFromServer() { //Calling any webservice to get data Thread.Sleep(TimeSpan.FromSeconds(4)); dataFromServer = "Webservice data"; autoResetEvent.Set(); } }
