|
另一個(gè)同步策略是手控技術(shù),System.Threading命名空間中的一些可以用于手控同步的類。ManualResetEvent類用來使線程處于等待狀態(tài),它有2種狀態(tài):有信號(hào)(True)或無信號(hào)(False)。還有2個(gè)重要方法:Reset()和Set()。
下面代碼說明Reset()方法的用法:
using System; using System.Threading;
namespace ManualReset { class Reset { [STAThread] static void Main() { ManualResetEvent manRE; manRE=new ManualResetEvent(true); // 賦給信號(hào)量 bool state=manRE.WaitOne(1000,true); Console.WriteLine("ManualResetEvent After first waitone "+state);
manRE.Reset(); //設(shè)置ManualResetEvent狀態(tài)為無信號(hào)量 state=manRE.WaitOne(5000,true); Console.WriteLine("ManualResetEvent After second waitone "+state); } } }
運(yùn)行結(jié)果:
下面代碼說明Set()方法的用法:
using System; using System.Threading; namespace ManualSet { class Set { [STAThread] static void Main(string[] args) { ManualResetEvent manRE; manRE=new ManualResetEvent(false); Console.WriteLine("Before waitone"); bool state=manRE.WaitOne(5000,true); Console.WriteLine("ManualResetEvent After first waitone "+state);
manRE.Set(); //將其狀態(tài)設(shè)為有信號(hào)量 Thread.Sleep(3000); state=manRE.WaitOne(5000,true); Console.WriteLine("ManualResetEvent After second waitone "+state); } } }
運(yùn)行結(jié)果:
|
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!