學習筆記——並行程式設計Parallel
Parallel 並行運算
參考資料:http://www.cnblogs.com/woxpp/p/3925094.html
1.並行運算
使用Parallel並行運算時,跟task很像,相當於task+waitall 啟動多個執行緒計算 主執行緒也參與計算,就是節約了一個執行緒
Parallel.Invoke(() => this.DoSomethingLong("btnParallel_Click_002"),
() => this.DoSomethingLong("btnParallel_Click_001"),
() => this.DoSomethingLong("btnParallel_Click_003"),
() => this.DoSomethingLong("btnParallel_Click_004"),
() => this.DoSomethingLong("btnParallel_Click_005"));
2.使用方法:
2.1.Parallel.For
eg:Parallel.For(0, 5, t =>
{
this.DoSomethingLong($"btnParallel_Click_00{t}");
});
2.2.Parallel.Foreach
eg:Parallel.ForEach(new int[] { 0, 1, 2, 3, 4 }, t =>
{
this.DoSomethingLong($"btnParallel_Click_00{t}");
});
2.3.設定並行運算執行緒數量
ParallelOptions options = new ParallelOptions()
{
MaxDegreeOfParallelism = 3
};
Parallel.ForEach(new int[] { 0, 1, 2, 3, 4 }, options, t =>
{
this.DoSomethingLong($"btnParallel_Click_00{t}");
});
或者
Parallel.ForEach(new int[] { 0, 1, 2, 3, 4 }, options, (t, state) =>
{
this.DoSomethingLong($"btnParallel_Click_00{t}");
//state.Stop();//結束全部的
//state.Break();//停止當前的
//return;
});