PLINQ および TPL のラムダ式

タスク並列ライブラリ (TPL: Task Parallel Library) には、デリゲートの System.Func<TResult> 系または System.Action 系を入力パラメーターとして取得する多くのメソッドが用意されています。 これらのデリゲートを使用して、カスタムのプログラム ロジックを並列ループ、タスク、またはクエリに渡します。 PLINQ と同様に、TPL のコード例では、ラムダ式を使用してこれらのデリゲートのインスタンスをインライン コード ブロックとして作成しています。 ここでは、Func および Action について簡単に紹介し、タスク並列ライブラリと PLINQ のラムダ式を使用する方法について説明します。

メモ   一般的なデリゲートの詳細については、「デリゲート (C# プログラミング ガイド)」および「デリゲート (Visual Basic)」を参照してください。 C# および Visual Basic におけるラムダ式の詳細については、「ラムダ式 (C# プログラミング ガイド)」および「ラムダ式 (Visual Basic)」を参照してください。

Func デリゲート

Func デリゲートは、値を返すメソッドをカプセル化します。 Func シグネチャでは、常に最後または右端の型パラメーターで戻り値の型が指定されます。 コンパイラ エラーの一般的な原因の 1 つは、System.Func<T, TResult> に 2 つの入力パラメーターを渡そうとすることです。実際には、この型が受け取る入力パラメーターは 1 つだけです。 Framework クラス ライブラリでは、System.Func<TResult>System.Func<T, TResult>System.Func<T1, T2, TResult> などから System.Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> まで、17 の Func のバージョンが定義されています。

Action デリゲート

System.Action デリゲートは、値を返さないメソッド (Visual Basic の Sub) または void を返すメソッドをカプセル化します。 Action の型シグネチャでは、型パラメーターは入力パラメーターのみを表します。 Func と同様、Framework クラス ライブラリでは 17 バージョンの Action が定義されています。この中には型パラメーターを持たないものから、16 の型パラメーターを持つものまであります。

Parallel.ForEach<TSource, TLocal>(IEnumerable<TSource>, Func<TLocal>, Func<TSource, ParallelLoopState, TLocal, TLocal>, Action<TLocal>) メソッドの次の例は、ラムダ式を使用して Func デリゲートと Action デリゲートの両方を表現する方法を示しています。

Imports System.Threading
Imports System.Threading.Tasks
Module ForEachDemo

    ' Demonstrated features:
    '   Parallel.ForEach()
    '   Thread-local state
    ' Expected results:
    '   This example sums up the elements of an int[] in parallel.
    '   Each thread maintains a local sum. When a thread is initialized, that local sum is set to 0.
    '   On every iteration the current element is added to the local sum.
    '   When a thread is done, it safely adds its local sum to the global sum.
    '   After the loop is complete, the global sum is printed out.
    ' Documentation:
    '   https://msdn.microsoft.com/en-us/library/dd990270(VS.100).aspx
    Private Sub ForEachDemo()
        ' The sum of these elements is 40.
        Dim input As Integer() = {4, 1, 6, 2, 9, 5, _
        10, 3}
        Dim sum As Integer = 0

        Try
            ' source collection
            Parallel.ForEach(input,
                             Function()
                                 ' thread local initializer
                                 Return 0
                             End Function,
                             Function(n, loopState, localSum)
                                 ' body
                                 localSum += n
                                 Console.WriteLine("Thread={0}, n={1}, localSum={2}", Thread.CurrentThread.ManagedThreadId, n, localSum)
                                 Return localSum
                             End Function,
                             Sub(localSum)
                                 ' thread local aggregator
                                 Interlocked.Add(sum, localSum)
                             End Sub)

            Console.WriteLine(vbLf & "Sum={0}", sum)
        Catch e As AggregateException
            ' No exception is expected in this example, but if one is still thrown from a task,
            ' it will be wrapped in AggregateException and propagated to the main thread.
            Console.WriteLine("Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED." & vbLf & "{0}", e)
        End Try
    End Sub


End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class ForEachWithThreadLocal
{
    // Demonstrated features:
    //      Parallel.ForEach()
    //      Thread-local state
    // Expected results:
    //      This example sums up the elements of an int[] in parallel.
    //      Each thread maintains a local sum. When a thread is initialized, that local sum is set to 0.
    //      On every iteration the current element is added to the local sum.
    //      When a thread is done, it safely adds its local sum to the global sum.
    //      After the loop is complete, the global sum is printed out.
    // Documentation:
    //      https://msdn.microsoft.com/en-us/library/dd990270(VS.100).aspx
    static void Main()
    {
        // The sum of these elements is 40.
        int[] input = { 4, 1, 6, 2, 9, 5, 10, 3 };
        int sum = 0;

        try
        {
            Parallel.ForEach(
                    input,                          // source collection
                    () => 0,                         // thread local initializer
                    (n, loopState, localSum) =>      // body
                    {
                        localSum += n;
                        Console.WriteLine("Thread={0}, n={1}, localSum={2}", Thread.CurrentThread.ManagedThreadId, n, localSum);
                        return localSum;
                    },
                    (localSum) => Interlocked.Add(ref sum, localSum)                 // thread local aggregator
                );

            Console.WriteLine("\nSum={0}", sum);
        }
        // No exception is expected in this example, but if one is still thrown from a task,
        // it will be wrapped in AggregateException and propagated to the main thread.
        catch (AggregateException e)
        {
            Console.WriteLine("Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e);
        }
    }

}

参照

概念

.NET Framework の並列プログラミング