C# -- 使用线程池 ThreadPool 执行多线程任务
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; } }
执行结果: