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;
});