方法: 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 月 |
使用法と高速化に関する説明を 追加。 |
カスタマー フィードバック |