.Net(C#) Parallel.For和Parallel.Invoke介绍及使用方法
时间:2022-09-04
1、Parallel.For()方法
Parallel.For(intfromInclude,inttoExclude,Action<int>body)
与for循环类似,执行并行的循环,相当于每次循环一个线程
Parallel.For(0,10,(i)=>{ Console.Write(i); });
完整示例代码:
using System; using System.Threading; using System.Threading.Tasks; public >Example { public static void Main() { var rnd = new Random(); int breakIndex = rnd.Next(1, 11); Nullable<long> lowest = new Nullable<long>(); Console.WriteLine("Will call Break at iteration {0}\n", breakIndex); var result = Parallel.For(1, 101, (i, state) => { Console.WriteLine("Beginning iteration {0}", i); int delay; Monitor.Enter(rnd); delay = rnd.Next(1, 1001); Monitor.Exit(rnd); Thread.Sleep(delay); if (state.ShouldExitCurrentIteration) { if (state.LowestBreakIteration < i) return; } if (i == breakIndex) { Console.WriteLine("Break in iteration {0}", i); state.Break(); if (state.LowestBreakIteration.HasValue) if (lowest < state.LowestBreakIteration) lowest = state.LowestBreakIteration; else lowest = state.LowestBreakIteration; } Console.WriteLine("Completed iteration {0}", i); }); if (lowest.HasValue) Console.WriteLine("\nLowest Break Iteration: {0}", lowest); else Console.WriteLine("\nNo lowest break iteration."); } }
2、Parallel.Invoke()方法
Parallel.Invoke(ParallelOptions,Action[])
对给定任务实现并行执行
varall=new[]{0,1,2,3,4,5,6,7,8,9};
Parallel.ForEach(all,(i)=>{
Console.Write($"{i}");
});
完整示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; >ParallelInvokeDemo {//显示功能: // Parallel.Invoke() //预期结果: //执行每个任务的线程可能不同。 //线程分配在不同的执行中可能不同。 //这些任务可以按任何顺序执行。 //文档: // http://msdn.microsoft.com/library/dd783942(VS.100). aspx static void Main() { try { Parallel.Invoke( BasicAction, // Param #0 - static method () => // Param #1 - lambda expression { Console.WriteLine("Method=beta, Thread={0}", Thread.CurrentThread.ManagedThreadId); }, delegate() // Param #2 - in-line delegate { Console.WriteLine("Method=gamma, Thread={0}", Thread.CurrentThread.ManagedThreadId); } ); } //本例中不期望出现异常,但如果仍然从任务中抛出异常, //它将被包装在AggregateException中,并传播到主线程。 catch (AggregateException e) { Console.WriteLine("An action has thrown an exception. THIS WAS UNEXPECTED.\n{0}", e.InnerException.ToString()); } } static void BasicAction() { Console.WriteLine("Method=alpha, Thread={0}", Thread.CurrentThread.ManagedThreadId); } }
注意:所有的并行开发不是简单的以为只要将For换成Parallel.For或调用Parallel.Invoke()执行任务这样简单。
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。