C# -- 使用 Task 執行多線程任務 1. 使用 Task 執行多線程任務 執行結果: 2. 等待Task多線程任務執行完成 執行結果: ...
C# -- 使用 Task 執行多線程任務
1. 使用 Task 執行多線程任務
class Program { static void Main(string[] args) { Task task1 = new Task(() => { 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); }); Task task2 = new Task(() => { Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(20000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); Task task3 = new Task(() => { Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(15000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); task1.Start(); task2.Start(); task3.Start(); Console.ReadKey(); } static long SumNumbers(int count) { long sum = 0; for (int i = 0; i < count; i++) { sum += i; } Thread.Sleep(3000); return sum; } }
執行結果:
2. 等待Task多線程任務執行完成
class Program { static void Main(string[] args) { Task task1 = new Task(() => { 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); }); Task task2 = new Task(() => { Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(20000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); Task task3 = new Task(() => { Console.WriteLine("線程ID:{0},開始執行", Thread.CurrentThread.ManagedThreadId); Stopwatch stw = new Stopwatch(); stw.Start(); long result = SumNumbers(15000000); stw.Stop(); Console.WriteLine("線程ID:{0},執行完成,執行結果:{1},執行用時{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds); }); List<Task> listTask = new List<Task>(); listTask.Add(task1); listTask.Add(task2); listTask.Add(task3); task1.Start(); task2.Start(); task3.Start(); Task.WaitAll(listTask.ToArray()); 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; } }
執行結果: