【问题标题】:System.Threading.Task library in .net specifically Parallel.ForEach.net 中的 System.Threading.Task 库,特别是 Parallel.ForEach
【发布时间】:2012-10-31 14:28:41
【问题描述】:

我查看了微软在 MSDN 上的 Tasks 教程......它显示的内容很好,但我仍然有疑问在那里的例子......在这个 URL 找到:MSDN Link

他们展示了一个示例,其中展示了 Parallel.ForEach() 静态方法调用。在那个方法调用中,它们有四个参数……第一个参数必须是一个整数数组吗?或者它可能是所有线程都在处理的任何类型的集合或对象?看起来第二个参数是一个 Action,它是一个不返回值(或 void)的委托。第二个变量到底是干什么用的?线程本地初始化程序?为什么初始化为0?这里到底设置了什么?第三个参数只是一个委托(或我想用的函数点)是 lambda 表达式的右侧实际函数吗?例如,我可以把一个实际函数的名称放在那一边,而不必在那里写出来吗?比如……

    public int localSum(int n, ParallelLoopState loopState, int localSum) {
        localSum += n;
        Console.WriteLine("Thread={0}, n={1}, localSum={2}", Thread.CurrentThread.ManagedThreadId, n, localSum);
        return localSum;
    }

(n, loopState, localSum) => localSum(int n, ParallelLoopState loopState, int localSum),

【问题讨论】:

标签: c# .net multithreading parallel-extensions


【解决方案1】:

看起来像this overload

public static ParallelLoopResult ForEach<TSource, TLocal>(
    IEnumerable<TSource> source,
    Func<TLocal> localInit,
    Func<TSource, ParallelLoopState, TLocal, TLocal> body,
    Action<TLocal> localFinally
)

你在哪里:

Parameters

source
    Type: System.Collections.Generic.IEnumerable<TSource>

    An enumerable data source.

localInit
    Type: System.Func<TLocal>

    The function delegate that returns the initial state of the local data for each task.

body
    Type: System.Func<TSource, ParallelLoopState, TLocal, TLocal>

    The delegate that is invoked once per iteration.

localFinally
    Type: System.Action<TLocal>

    The delegate that performs a final action on the local state of each task.

【讨论】:

    【解决方案2】:

    第二个参数是一个Action&lt;int&gt;,它就像一个普通的foreach循环体。使用Parallel.ForEach 最简单的方法是双参数重载:

    Parallel.ForEach(myIntegers, i => loopBody(i));
    
    // non-parallel equivalent
    foreach(int i in myIntegers)
    {
        loopBody(i);
    }
    

    myIntegers 可以是任何IEnumerable&lt;int&gt;,因此不一定是数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      相关资源
      最近更新 更多