HOW TO:在 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 月 |
加入有關使用方式和 加速的比較注意事項。 |
客戶回函。 |