AutoResetEvent 可以從一個線程向另一個線程發送通知,可以通知等待的線程有某事件發生。
通俗的來講只有等Set()成功運行後WaitOne()才能夠運行
Set是發信號,WaitOne是等待信號
1 public class AutoResetEventTest 2 { 3 4 private AutoResetEvent autoReset = null; 5 6 public AutoResetEventTest(AutoResetEvent resetEvent) 7 { 8 autoReset = resetEvent; 9 } 10 11 public void Task() 12 { 13 while (true) 14 { 15 autoReset.WaitOne(); 16 Console.WriteLine($"開始執行任務"); 17 } 18 } 19 20 21 }
1 public class Program 2 { 3 const int times = 10; 4 static AutoResetEvent myEvent = new AutoResetEvent(false); 5 static void Main(string[] args) 6 { 7 Thread thread = new Thread(() => new AutoResetEventTest(myEvent).Task()); 8 thread.Start(); 9 for (int i = 1; i < times; i++) 10 { 11 Console.WriteLine($"第{i}次傳遞信號"); 12 myEvent.Set(); 13 Thread.Sleep(TimeSpan.FromSeconds(3)); 14 } 15 Console.ReadLine(); 16 } 17 18 }
執行結果