C# -- 使用線程池 ThreadPool 執行多線程任務 1. 使用線程池 執行結果: 2. 等待線程池的線程執行 執行結果: ...
C# -- 使用線程池 ThreadPool 執行多線程任務
1. 使用線程池
class Program { static void Main(string[] args) { WaitCallback wc1 = s =>{ Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(10000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},",Thread.CurrentThread.ManagedThreadId,result,stw.ElapsedMilliseconds); }; WaitCallback wc2 = s => { Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(10000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }; WaitCallback wc3 = s => { Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(10000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }; ThreadPool.QueueUserWorkItem(wc1); ThreadPool.QueueUserWorkItem(wc2); ThreadPool.QueueUserWorkItem(wc3); Console.ReadKey(); } static long SumNumbers(int count) { long sum = 0; for (int i = 0; i < count; i++) { sum += i; } Thread.Sleep(1000); return sum; } }
執行結果:
2. 等待線程池的線程執行
class Program { static void Main(string[] args) { using (ManualResetEvent m1 = new ManualResetEvent(false)) using (ManualResetEvent m2 = new ManualResetEvent(false)) using (ManualResetEvent m3 = new ManualResetEvent(false)) { ThreadPool.QueueUserWorkItem( s =>{ Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(10000000); stw.Stop(); m1.Set(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); ThreadPool.QueueUserWorkItem( s =>{ Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(10000000); stw.Stop(); m2.Set(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); ThreadPool.QueueUserWorkItem( s =>{ Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(10000000); stw.Stop(); m3.Set(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); //等待線程池的線程執行 m1.WaitOne(); m2.WaitOne(); m3.WaitOne(); Console.WriteLine("所有線程執行完成"); } Console.ReadKey(); } static long SumNumbers(int count) { long sum = 0; for (int i = 0; i < count; i++) { sum += i; } Thread.Sleep(3000); return sum; } }
執行結果: