資源簡介
AutoResetEvent 允許線程通過發(fā)信號(hào)互相通信。通常,此通信涉及線程需要獨(dú)占訪問的資源。
線程通過調(diào)用 AutoResetEvent 上的 WaitOne 來等待信號(hào)。如果 AutoResetEvent 處于非終止?fàn)顟B(tài),則該線程阻塞,并等待當(dāng)前控制資源的線程通過調(diào)用 Set 發(fā)出資源可用的信號(hào)。
調(diào)用 Set 向 AutoResetEvent 發(fā)信號(hào)以釋放等待線程。AutoResetEvent 將保持終止?fàn)顟B(tài),直到一個(gè)正在等待的線程被釋放,然后自動(dòng)返回非終止?fàn)顟B(tài)。如果沒有任何線程在等待,則狀態(tài)將無限期地保持為終止?fàn)顟B(tài)
線程通過調(diào)用 AutoResetEvent 上的 WaitOne 來等待信號(hào)。如果 AutoResetEvent 處于非終止?fàn)顟B(tài),則該線程阻塞,并等待當(dāng)前控制資源的線程通過調(diào)用 Set 發(fā)出資源可用的信號(hào)。
調(diào)用 Set 向 AutoResetEvent 發(fā)信號(hào)以釋放等待線程。AutoResetEvent 將保持終止?fàn)顟B(tài),直到一個(gè)正在等待的線程被釋放,然后自動(dòng)返回非終止?fàn)顟B(tài)。如果沒有任何線程在等待,則狀態(tài)將無限期地保持為終止?fàn)顟B(tài)
代碼片段和文件信息
using?System;
using?System.Threading;
namespace?AutoResetEvent_Examples
{
????class?MyMainClass
????{
????????//Initially?not?signaled.
????????const?int?numIterations?=?100;
????????static?AutoResetEvent?myResetEvent?=?new?AutoResetEvent(false);
????????static?int?number;
????????static?void?Main()
????????{
????????????//Create?and?start?the?reader?thread.
????????????Thread?myReaderThread?=?new?Thread(new?ThreadStart(MyReadThreadProc));
????????????myReaderThread.Name?=?“ReaderThread“;
????????????myReaderThread.Start();
????????????for?(int?i?=?1;?i?<=?numIterations;?i++)
????????????{
????????????????Console.WriteLine(“Writer?thread?writing?value:?{0}“?i);
????????????????number?=?i;
????????????????//Signal?that?a?value?has?been?written.
????????????????myResetEvent.Set();
????????????????//Give?the?Reader?thread?an?opportunity?to?act.
????????????????Thread.Sleep(0);
????????????}
????????????//Terminate?the?reader?thread.
????????????myReaderThread.Abort();
????????}
????????static?void?MyReadThreadProc()
????????{
????????????while?(true)
????????????{
????????????????//The?value?will?not?be?read?until?the?writer?has?written
????????????????//?at?least?once?since?the?last?read.
????????????????myResetEvent.WaitOne();
????????????????Console.WriteLine(“{0}?reading?value:?{1}“?Thread.CurrentThread.Name?number);
????????????}
????????}
????}
}
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????文件???????1433??2008-09-26?14:44??Program.cs
-----------?---------??----------?-----??----
?????????????????1433????????????????????1
評(píng)論
共有 條評(píng)論