本文主要介绍.Net(C#)中Parallel.For和Parallel.Invoke相关介绍,及使用方法示例代码。

1、Parallel.For()方法

Parallel.For(int fromInclude, int toExclude, Action<int> body)

与for循环类似,执行并行的循环,相当于每次循环一个线程

官方文档https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.parallel.for?redirectedfrom=MSDN&view=netframework-4.7.2

Parallel.For(0, 10, (i) => {
    Console.Write(i);
});

完整示例代码

using System;
using System.Threading;
using System.Threading.Tasks;
public class 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[])

对给定任务实现并行执行

官方文档https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.parallel.invoke?redirectedfrom=MSDN&view=netframework-4.7.2

var all = 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;
    class 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()执行任务这样简单。