在開發過程當中,常常須要多個任務並行的執行的場景,同時任務之間又須要前後依賴的關係。針對這樣的處理邏輯,一般會採用多線程的程序模型來實現。多線程
好比A、B、C三個線程,A和B須要同時啓動,並行處理,且B須要依賴A完成,在進行後續的處理,C須要B完成後開始處理。框架
針對這個場景,使用了ThreadPool,ManualResetEvent等.net框架內置的類功能進行了模擬,實現代碼以下:oop
public class MultipleThreadCooperationSample { public static ManualResetEvent eventAB = new ManualResetEvent(false); public static ManualResetEvent eventBC = new ManualResetEvent(false); public static int Main(string[] args) { //so called thread A ThreadPool.QueueUserWorkItem(new WaitCallback(d => { Console.WriteLine("Start A thread"); Thread.Sleep(4000); eventAB.Set(); })); //thread A ThreadPool.QueueUserWorkItem(new WaitCallback(d => { Console.WriteLine("Start B thread and wait A thread to finised."); eventAB.WaitOne(); Console.WriteLine("Process something within B thread"); Thread.Sleep(4000); eventBC.Set(); })); eventBC.WaitOne(Timeout.Infinite, true); //thread C ThreadPool.QueueUserWorkItem(new WaitCallback(d => { Console.WriteLine("From C thread, everything is done."); })); Console.ReadLine(); return 0; } }
運行結果以下:spa