ManualResetEvent用法
生活随笔
收集整理的這篇文章主要介紹了
ManualResetEvent用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ManualResetEvent 允許線程通過發信號互相通信。通常,此通信涉及一個線程在其他線程進行之前必須完成的任務。
public static ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent建立時是把false作為start的初始狀態,這個類用于通知另一個線程,讓它等待一個或多個線程。注意,為了通知或監聽同一個線程,所有的其它線程都能訪問那個類。
等待線程這樣寫:
? mre.WaitOne();
這將引起等待線程無限期的阻塞并等待類來通知。
發信號的線程應該這樣:
? mre.Set();
這樣類就會被通知,值變成true,等待線程就會停止等待。在通知事件發生后,我們就可以使用下面語句把線程置于非終止狀態,導致線程阻止:
? mre.Reset();
一個測試的例子:
using?System.Threading;
namespace?ThreadingTester
{
????class?ThreadClass
????{
????????public?static?ManualResetEvent?mre?=?new?ManualResetEvent(false);
????????public?static?void?trmain()
????????{
????????????Thread?tr?=?Thread.CurrentThread;
????????????Console.WriteLine("thread:?waiting?for?an?event");
????????????mre.WaitOne();
????????????Console.WriteLine("thread:?got?an?event");
????????????for?(int?x?=?0;?x?<?10;?x++)
????????????{
????????????????Thread.Sleep(1000);
????????????????mre.WaitOne();
????????????????Console.WriteLine(tr.Name?+?":?"?+?x);
????????????}
????????}
????????static?void?Main(string[]?args)
????????{
????????????Thread?thrd1?=?new?Thread(new?ThreadStart(trmain));
????????????thrd1.Name?=?"thread1";
????????????thrd1.Start();
????????????for?(int?x?=?0;?x?<?10;?x++)
????????????{
????????????????Thread.Sleep(900);
????????????????Console.WriteLine("Main:"?+?x);
????????????????if?(5?==?x)?mre.Set();
????????????????if?(6?==?x)?mre.Reset();
????????????????if?(8?==?x)?mre.Set();
????????????}
????????????while?(thrd1.IsAlive)
????????????{
????????????????Thread.Sleep(1000);
????????????????Console.WriteLine("Main:?waiting?for?thread?to?stop");
????????????}
????????}
????}
}
運行的結果為:
thread: waiting for an event
Main:0
Main:1
Main:2
Main:3
Main:4
Main:5
thread: got an event
Main:6
Main:7
Main:8
thread1: 0
Main:9
thread1: 1
Main: waiting for thread to stop
thread1: 2
Main: waiting for thread to stop
thread1: 3
Main: waiting for thread to stop
thread1: 4
Main: waiting for thread to stop
thread1: 5
Main: waiting for thread to stop
thread1: 6
Main: waiting for thread to stop
thread1: 7
Main: waiting for thread to stop
thread1: 8
Main: waiting for thread to stop
thread1: 9
Main: waiting for thread to stop
轉載于:https://www.cnblogs.com/fengfeng/archive/2008/06/24/1229037.html
總結
以上是生活随笔為你收集整理的ManualResetEvent用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 控件中的Events个人理解。
- 下一篇: 武器属性跟技能属性有关吗?