資源簡介
AutoResetEvent 允許線程通過發信號互相通信。通常,此通信涉及線程需要獨占訪問的資源。
線程通過調用 AutoResetEvent 上的 WaitOne 來等待信號。如果 AutoResetEvent 處于非終止狀態,則該線程阻塞,并等待當前控制資源的線程通過調用 Set 發出資源可用的信號。
調用 Set 向 AutoResetEvent 發信號以釋放等待線程。AutoResetEvent 將保持終止狀態,直到一個正在等待的線程被釋放,然后自動返回非終止狀態。如果沒有任何線程在等待,則狀態將無限期地保持為終止狀態
線程通過調用 AutoResetEvent 上的 WaitOne 來等待信號。如果 AutoResetEvent 處于非終止狀態,則該線程阻塞,并等待當前控制資源的線程通過調用 Set 發出資源可用的信號。
調用 Set 向 AutoResetEvent 發信號以釋放等待線程。AutoResetEvent 將保持終止狀態,直到一個正在等待的線程被釋放,然后自動返回非終止狀態。如果沒有任何線程在等待,則狀態將無限期地保持為終止狀態
代碼片段和文件信息
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);
????????????}
????????}
????}
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????1433??2008-09-26?14:44??Program.cs
-----------?---------??----------?-----??----
?????????????????1433????????????????????1
評論
共有 條評論