在多線程編程中,線程之間的同步和通信是一個常見的需求。例如,我們可能需要一個子線程完成某些任務后通知主線程,并由主線程執行特定的動作。本文將基于一個示例程序,詳細講解如何使用 AutoResetEvent?來實現這種場景。
示例代碼:
using System;
using System.Threading;class Program
{static void Main(string[] args){Console.WriteLine("Main thread started.");using (AutoResetEvent workDoneEvent = new AutoResetEvent(false)){// 創建并啟動子線程Thread workerThread = new Thread(() => DoWork(workDoneEvent));workerThread.Start();// 主線程繼續做其他事情,不會被阻塞for (int i = 0; i < 5; i++){Console.WriteLine("Main thread is working...");Thread.Sleep(1000);}// 等待子線程的通知int pollInterval = 500; // 輪詢間隔(毫秒)while (true){if (workDoneEvent.WaitOne(0)){ExecuteCallback();break;}Thread.Sleep(pollInterval);}}Console.WriteLine("Main thread finished.");}static void DoWork(AutoResetEvent workDoneEvent){Console.WriteLine("Worker thread started.");Thread.Sleep(100); // 模擬工作Console.WriteLine("Worker thread finished.");// 通知主線程workDoneEvent.Set();}static void ExecuteCallback(){Thread.Sleep(500); // 模擬動作執行Console.WriteLine("Callback is invoked on Main thread.");}
}
程序的功能描述
上述代碼實現了一個典型的多線程場景:
- 主線程啟動后,創建并啟動一個子線程。
- 子線程模擬執行某些工作(通過?Thread.Sleep(100)?模擬耗時操作)。
- 子線程完成后,通過?AutoResetEvent?通知主線程。
- 主線程收到通知后,執行特定的動作(ExecuteCallback?方法)。
?
?
?
?