方法: 単純な Parallel.ForEach ループを記述する
この例では、Parallel.ForEach ループを使用して System.Collections.IEnumerable データ ソースまたは System.Collections.Generic.IEnumerable<T> データ ソースを対象にデータを並列化する方法を示します。
![]() |
---|
ここでは、ラムダ式を使用して PLINQ でデリゲートを定義します。C# または Visual Basic のラムダ式についての情報が必要な場合は、「PLINQ および TPL のラムダ式」を参照してください。 |
使用例
' How to: Write a Simple Parallel.ForEach Loop
' IMPORTANT!!!: Add reference to System.Drawing.dll
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Drawing
Module ForEachDemo
Sub Main()
' A simple source for demonstration purposes. Modify this path as necessary.
Dim files As String() = System.IO.Directory.GetFiles("C:\Users\Public\Pictures\Sample Pictures", "*.jpg")
Dim newDir As String = "C:\Users\Public\Pictures\Sample Pictures\Modified"
System.IO.Directory.CreateDirectory(newDir)
' Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
' Be sure to add a reference to System.Drawing.dll.
Parallel.ForEach(files, Sub(currentFile)
' The more computational work you do here, the greater
' the speedup compared to a sequential foreach loop.
Dim filename As String = System.IO.Path.GetFileName(currentFile)
Dim bitmap As New System.Drawing.Bitmap(currentFile)
bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone)
bitmap.Save(System.IO.Path.Combine(newDir, filename))
' Peek behind the scenes to see how work is parallelized.
' But be aware: Thread contention for the Console slows down parallel loops!!!
Console.WriteLine("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId)
'close lambda expression and method invocation
End Sub)
' Keep the console window open in debug mode.
Console.WriteLine("Processing complete. Press any key to exit.")
Console.ReadKey()
End Sub
End Module
namespace ForEachDemo
{
using System;
using System.Drawing; // requires system.Drawing.dll
using System.IO;
using System.Threading;
using System.Threading.Tasks;
class SimpleForEach
{
static void Main()
{
// A simple source for demonstration purposes. Modify this path as necessary.
string[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
string newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";
System.IO.Directory.CreateDirectory(newDir);
// Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
Parallel.ForEach(files, currentFile =>
{
// The more computational work you do here, the greater
// the speedup compared to a sequential foreach loop.
string filename = System.IO.Path.GetFileName(currentFile);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);
bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
bitmap.Save(System.IO.Path.Combine(newDir, filename));
// Peek behind the scenes to see how work is parallelized.
// But be aware: Thread contention for the Console slows down parallel loops!!!
Console.WriteLine("Processing {0} on thread {1}", filename,
Thread.CurrentThread.ManagedThreadId);
} //close lambda expression
); //close method invocation
// Keep the console window open in debug mode.
Console.WriteLine("Processing complete. Press any key to exit.");
Console.ReadKey();
}
}
}
ForEach ループは For ループと同様に動作します。 ソース コレクションがパーティション分割され、システム環境に基づいて複数のスレッドに処理がスケジュールされます。 システム上のプロセッサの数が多いほど、並列メソッドの実行速度は速くなります。 ソース コレクションの中には、ソースのサイズおよび実行される作業の種類によっては、順次ループが早くなるものがあります。 パフォーマンスの詳細については、「データとタスクの並列化における注意点」を参照してください。
並列ループの詳細については、「方法: 単純な Parallel.For ループを記述する」を参照してください。
非ジェネリック コレクションで ForEach を使用するには、次の例に示すように、Cast<TResult> 拡張メソッドを使用してコレクションをジェネリック コレクションに変換します。
Parallel.ForEach(nonGenericCollection.Cast(Of Object), _
Sub(currentElement)
' ... work with currentElement
End Sub)
Parallel.ForEach(nonGenericCollection.Cast<object>(),
currentElement =>
{
});
Parallel LINQ (PLINQ) を使用して、IEnumerable<T> データ ソースの処理を並列化することもできます。 PLINQ により、宣言型のクエリ構文を使用してループの動作を表現できます。 詳細については、「Parallel LINQ (PLINQ)」を参照してください。
コードのコンパイル
このコードをコピーして Visual Studio 2010 コンソール アプリケーション プロジェクトに貼り付けます。
System.Drawing.dll への参照を追加します。
F5 キーを押します。