如何:建立並執行簡單的 PLINQ 查詢

本文的範例示範如何對來源序列使用 ParallelEnumerable.AsParallel 擴充方法來建立簡單的平行 Language Integrated Query (LINQ) 查詢,以及使用 ParallelEnumerable.ForAll 方法執行查詢。

注意

本文件使用 Lambda 運算式來定義 PLINQ 中的委派。 如果您不熟悉 C# 或 Visual Basic 中的 Lambda 運算式,請參閱 PLINQ 和 TPL 中的 Lambda 運算式

範例

using System;
using System.Linq;

class ExampleForAll
{
    public static void Main()
    {
        var source = Enumerable.Range(100, 20000);

        // Result sequence might be out of order.
        var parallelQuery =
            from num in source.AsParallel()
            where num % 10 == 0
            select num;

        // Process result sequence in parallel
        parallelQuery.ForAll((e) => DoSomething(e));

        // Or use foreach to merge results first.
        foreach (var n in parallelQuery)
        {
            Console.WriteLine(n);
        }

        // You can also use ToArray, ToList, etc as with LINQ to Objects.
        var parallelQuery2 =
            (from num in source.AsParallel()
             where num % 10 == 0
             select num).ToArray();

        // Method syntax is also supported
        var parallelQuery3 =
            source.AsParallel()
                .Where(n => n % 10 == 0)
                .Select(n => n);

        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();
    }

    static void DoSomething(int _) { }
}

Public Class Program
    Public Shared Sub Main()
        Dim source = Enumerable.Range(100, 20000)

        ' Result sequence might be out of order.
        Dim parallelQuery = From num In source.AsParallel()
                            Where num Mod 10 = 0
                            Select num

        ' Process result sequence in parallel
        parallelQuery.ForAll(Sub(e)
                                 DoSomething(e)
                             End Sub)

        ' Or use For Each to merge results first
        ' as in this example, Where results must
        ' be serialized sequentially through static Console method.
        For Each n In parallelQuery
            Console.Write("{0} ", n)
        Next

        ' You can also use ToArray, ToList, etc, as with LINQ to Objects.
        Dim parallelQuery2 = (From num In source.AsParallel()
                              Where num Mod 10 = 0
                              Select num).ToArray()

        ' Method syntax is also supported
        Dim parallelQuery3 =
            source.AsParallel().Where(Function(n)
                                          Return (n Mod 10) = 0
                                      End Function).Select(Function(n)
                                                               Return n
                                                           End Function)

        For Each i As Integer In parallelQuery3
            Console.Write($"{i} ")
        Next


        Console.WriteLine()
        Console.WriteLine("Press any key to exit...")
        Console.ReadLine()
    End Sub

    ' A toy function to demonstrate syntax. Typically you need a more
    ' computationally expensive method to see speedup over sequential queries.
    Shared Sub DoSomething(ByVal i As Integer)
        Console.Write($"{Math.Sqrt(i):###.##} ")
    End Sub
End Class

此範例示範的是結果序列的順序並不重要時,建立與執行任何平行 LINQ 查詢的基本模式。 未排序的查詢通常比排序的查詢更快。 查詢會將來源分割成在多個執行緒上非同步執行的工作。 每項工作的完成順序不僅取決於處理分割中的項目時所涉及的工作量,也取決於一些外部因素,例如作業系統排程每個執行緒的方式。 這個範例是為了示範用法,執行速度可能比不上對應的循序 LINQ to Objects 查詢。 如需加速的詳細資訊,請參閱認識 PLINQ 中的加速。 如需如何在查詢中保留元素順序的詳細資訊,請參閱如何:控制 PLINQ 查詢中的順序

另請參閱