如何:在 PLINQ 中指定合并选项
更新:2010 年 5 月
此示例演示如何指定将应用于 PLINQ 查询中的所有后续运算符的合并选项。 您不必显式设置合并选项,但这样做可以改善性能。 有关合并选项的更多信息,请参见 PLINQ 中的合并选项。
警告 |
---|
本示例旨在演示用法,运行速度可能不如等效的顺序 LINQ to Objects 查询快。有关加速的更多信息,请参见了解 PLINQ 中的加速。 |
示例
下面的示例演示一个具有未排序的源的基本方案中合并选项的行为,并将高开销函数应用于每个元素。
Class MergeOptions2
Sub DoMergeOptions()
Dim nums = Enumerable.Range(1, 10000)
' Replace NotBuffered with AutoBuffered
' or FullyBuffered to compare behavior.
Dim scanLines = From n In nums.AsParallel().WithMergeOptions(ParallelMergeOptions.NotBuffered)
Where n Mod 2 = 0
Select ExpensiveFunc(n)
Dim sw = System.Diagnostics.Stopwatch.StartNew()
For Each line In scanLines
Console.WriteLine(line)
Next
Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.")
Console.ReadKey()
End Sub
' A function that demonstrates what a fly
' sees when it watches television :-)
Function ExpensiveFunc(ByVal i As Integer) As String
System.Threading.Thread.SpinWait(2000000)
Return String.Format("{0} *****************************************", i)
End Function
End Class
namespace MergeOptions
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
class Program
{
static void Main(string[] args)
{
var nums = Enumerable.Range(1, 10000);
// Replace NotBuffered with AutoBuffered
// or FullyBuffered to compare behavior.
var scanLines = from n in nums.AsParallel()
.WithMergeOptions(ParallelMergeOptions.NotBuffered)
where n % 2 == 0
select ExpensiveFunc(n);
Stopwatch sw = Stopwatch.StartNew();
foreach (var line in scanLines)
{
Console.WriteLine(line);
}
Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.",
sw.ElapsedMilliseconds);
Console.ReadKey();
}
// A function that demonstrates what a fly
// sees when it watches television :-)
static string ExpensiveFunc(int i)
{
Thread.SpinWait(2000000);
return String.Format("{0} *****************************************", i);
}
}
}
如果在生成第一个元素之前 AutoBuffered 选项引致令人不快的延迟,请尝试用 NotBuffered 选项更快更流畅地生成结果元素。
请参见
参考
概念
修订记录
日期 |
修订记录 |
原因 |
---|---|---|
2010 年 5 月 |
添加了有关用法与 加速的注释。 |
客户反馈 |