C# -- 使用 Task 执行多线程任务
1. 使用 Task 执行多线程任务
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Task task1 = new Task(() => { 6 Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId); 7 Stopwatch stw = new Stopwatch(); 8 stw.Start(); 9 long result = SumNumbers(10000000); 10 stw.Stop(); 11 Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); 12 }); 13 14 Task task2 = new Task(() => { 15 Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId); 16 Stopwatch stw = new Stopwatch(); 17 stw.Start(); 18 long result = SumNumbers(20000000); 19 stw.Stop(); 20 Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); 21 }); 22 23 Task task3 = new Task(() => { 24 Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId); 25 Stopwatch stw = new Stopwatch(); 26 stw.Start(); 27 long result = SumNumbers(15000000); 28 stw.Stop(); 29 Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); 30 }); 31 32 task1.Start(); 33 task2.Start(); 34 task3.Start(); 35 36 Console.ReadKey(); 37 } 38 39 static long SumNumbers(int count) 40 { 41 long sum = 0; 42 for (int i = 0; i < count; i++) 43 { 44 sum += i; 45 } 46 Thread.Sleep(3000); 47 return sum; 48 } 49 }
执行结果:
2. 等待Task多线程任务执行完成
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Task task1 = new Task(() => { 6 Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId); 7 Stopwatch stw = new Stopwatch(); 8 stw.Start(); 9 long result = SumNumbers(10000000); 10 stw.Stop(); 11 Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); 12 }); 13 14 Task task2 = new Task(() => { 15 Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId); 16 Stopwatch stw = new Stopwatch(); 17 stw.Start(); 18 long result = SumNumbers(20000000); 19 stw.Stop(); 20 Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); 21 }); 22 23 Task task3 = new Task(() => { 24 Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId); 25 Stopwatch stw = new Stopwatch(); 26 stw.Start(); 27 long result = SumNumbers(15000000); 28 stw.Stop(); 29 Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); 30 }); 31 32 List<Task> listTask = new List<Task>(); 33 listTask.Add(task1); 34 listTask.Add(task2); 35 listTask.Add(task3); 36 37 task1.Start(); 38 task2.Start(); 39 task3.Start(); 40 41 Task.WaitAll(listTask.ToArray()); 42 Console.WriteLine("所有线程执行完成。"); 43 44 Console.ReadKey(); 45 } 46 47 static long SumNumbers(int count) 48 { 49 long sum = 0; 50 for (int i = 0; i < count; i++) 51 { 52 sum += i; 53 } 54 Thread.Sleep(3000); 55 return sum; 56 } 57 }
执行结果: