Parallel 靜態類別平行化既有演算法Task<T> 取得回傳值預設資料類別 EmployeeList、服務 PayrollServices.GetPayrollDeduction() 模擬耗時運算。
for (int i = 0; i < employeeData.Count; i++)
{
decimal span = PayrollServices.GetPayrollDeduction(employeeData[i]);
}
輸出依序處理,總耗時約等於單項耗時總和。
Parallel.For 一鍵平行化Parallel.For(0, employeeData.Count, i =>
{
decimal span = PayrollServices.GetPayrollDeduction(employeeData[i]);
});
Lambda 表達式取代迴圈主體。執行順序非固定,多核心並行,總耗時大幅縮短(雙核心約減半)。

Parallel.ForEach 平行化 foreachParallel.ForEach(employeeData, ed => { ... });
同樣獲得平行效能提升。
Parallel.Invoke 平行化樹狀遍歷Parallel.Invoke(
() => WalkTree(node.Left),
() => WalkTree(node.Right)
);
遞迴分支並行執行,總時間顯著降低。

var task1 = Task.Factory.StartNew(() => PayrollServices.GetPayrollDeduction(employeeData[0]));
Wait() / WaitAll()task1.Wait();
Task.WaitAll(task1, task2, task3);
主執行緒阻塞直到所有工作完成,比 ThreadPool.QueueUserWorkItem + 手動事件更簡潔。
IsCompletedwhile (!task1.IsCompleted) { Thread.Sleep(1000); }
適用於需在工作完成前執行其他邏輯的場景。
ContinueWith()Task.Factory.StartNew(...)
.ContinueWith(...)
.ContinueWith(...);
保證執行順序,最後 Wait() 等待鏈尾。
Task<T> 取得回傳值var task = Task.Factory.StartNew(() => PayrollServices.GetPayrollDeduction(employeeData[0]));
decimal result = task.Result; // 若未完成則阻塞直到完成
適合「先啟動、稍後取值」模式。
var q = ParallelEnumerable.Select(
ParallelEnumerable.OrderBy(
ParallelEnumerable.Where(employeeData.AsParallel(), x => x.EmployeeID % 2 == 0),
x => x.EmployeeID),
x => PayrollServices.GetEmployeeInfo(x)).ToList();
var q = employeeData.AsParallel()
.Where(x => x.EmployeeID % 2 == 0)
.OrderBy(x => x.EmployeeID)
.Select(x => PayrollServices.GetEmployeeInfo(x))
.ToList();
僅在資料源加 .AsParallel() 即可平行化,語法極簡。
var q = from e in employeeData.AsParallel()
where e.EmployeeID % 2 == 0
orderby e.EmployeeID
select PayrollServices.GetEmployeeInfo(e);
平行執行順序不固定,效能顯著提升(雙核心約快一倍)。

Parallel、Task、PLINQ 三大核心Wait/WaitAll/IsCompleted/ContinueWith