在C#中實現多線程并行計算可以通過使用?Task
?和?Parallel
?類來實現。這里給出兩個簡單的示例,一個是使用?Task
,另一個是使用?Parallel.ForEach
。
使用 Task 進行多線程并行計算
using System;
using System.Threading.Tasks;class Program
{static void Main(){// Example: Calculating squares of numbers in parallelint[] numbers = { 1, 2, 3, 4, 5 };Task[] tasks = new Task[numbers.Length];for (int i = 0; i < numbers.Length; i++){int index = i; // To avoid the modified closure issuetasks[i] = Task.Run(() =>{int result = numbers[index] * numbers[index];Console.WriteLine($"Square of {numbers[index]} is {result}");});}Task.WaitAll(tasks); // Wait for all tasks to completeConsole.WriteLine("All tasks completed.");}
}
- 在上面的例子中,使用?
Task.Run()
?來啟動每個任務,計算數字的平方并輸出結果。Task.WaitAll(tasks)
?確保所有任務執行完畢后程序繼續執行。
使用 Parallel.ForEach 進行多線程并行計算
using System;
using System.Threading.Tasks;class Program
{static void Main(){// Example: Calculating squares of numbers in parallel using Parallel.ForEachint[] numbers = { 1, 2, 3, 4, 5 };Parallel.ForEach(numbers, number =>{int result = number * number;Console.WriteLine($"Square of {number} is {result}");});Console.WriteLine("All tasks completed.");}
}
- 在這個例子中,使用?
Parallel.ForEach
?來并行遍歷數組?numbers
,對每個元素進行平方計算并輸出結果。這種方式簡化了多線程編程,由 .NET 庫自動管理任務的分配和執行。
注意事項
- 在進行并行計算時,要注意數據的共享和同步問題,確保線程安全性。
- 使用?
Task
?和?Parallel
?類可以簡化多線程編程,同時利用現代多核處理器的能力提升應用程序的性能。
這些示例展示了在C#中如何利用多線程進行并行計算,可以根據具體需求和任務復雜性進行進一步的擴展和優化。