如何:创建并执行简单的 PLINQ 查询
本文中的示例演示如何通过对源序列使用 ParallelEnumerable.AsParallel 扩展方法来创建一个简单的并行语言集成查询 (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 查询中控制排序。
请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈