并行编程Parallel三个方法For,Foreach,Invoke的使用
Parallel.For(int fromInclusive, int toExclusive, Func<TLocal> localInit, Func<int, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally)
类似的Parallel.Foreach()
fromInclusive:开始索引(包含此索引)
toExclusive:结束索引(不包含次索引)
localInit:分区初始化;返回值:分区初始化结果
body:每个迭代执行的函数体;参数1:索引;参数3:执行结果;返回值:执行结果,最终有几个分区返回几个结果,由localFinally函数汇总;
localFinally:对每个分区的结果处理
int total = 0; IList<int> list = new List<int>(100); //分区 并行计算 Parallel.For(0, 100//数组的累计运算 , () => { return 1; } //分区初始化数据 , (index, loop, local) => { lock (list) { list.Add(System.Threading.Thread.CurrentThread.ManagedThreadId); } Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId); return local += index;//每个分区分别执行 } , local/*每个分区的结果*/ => { System.Threading.Interlocked.Add(ref total, local); });//汇总分区结果 Console.WriteLine("并行" + total); total = 0; for (int i = 0; i < 100; i++) { total += i; } IEnumerable<int> iee = list.Distinct(); Console.WriteLine("串行:" + total); Console.ReadKey();
Parallel.Invoke(params Action[] actions)
Parallel.Invoke(
() => { Console.WriteLine("action1"); }
, () => { Console.WriteLine("action2"); }
, () => { Console.WriteLine("action3"); });
注意:如果单个并行计算消耗很小,此时多任务并行效率低于串行计算
待了解:分区函数internal RangeManager(long nFromInclusive, long nToExclusive, long nStep, int nNumExpectedWorkers)