سؤال

I looked at microsoft's tutorial on Tasks on MSDN... It was good for what it showed, but I still have questions In there example... found at this URL: MSDN Link

They show an example where they show a Parallel.ForEach() static method call. In that method call they have four parameters... Does the first Parameter have to be an Array of Ints? Or could it be a collection or object of any kind that all the thread are working on? Looks like the second parameter is an Action, which is a delegate that doesn't return a value (or a void). What the heck is that second variable for? Thread Local initializer? Why Initialize to 0? What the hell is being set here? The 3rd parameter is just a delegate (or a function point as I like to think of them with) is the right side of the lambda expression the actual function? for instance, could I put the name of an actual function on that side without having to write it out right there? For example...

    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),
هل كانت مفيدة؟

المحلول

Looks like this overload:

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

where you have:

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.

نصائح أخرى

The second parameter is an Action<int> which is like an ordinary foreach loop's body. The simplest way to use Parallel.ForEach is the two-parameter overload:

Parallel.ForEach(myIntegers, i => loopBody(i));

// non-parallel equivalent
foreach(int i in myIntegers)
{
    loopBody(i);
}

myIntegers can be any IEnumerable<int> and must therefore not necessarily be an array.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top