Parallel.For döngüsü, bir döngüde her yineleme başına bir temsilci çağırmak suretiyle bir döngüde işi yürütmek için ThreadPool'u kullanır.
aşağıdaki gibi sunulabilir nasıl Parallel.For eserler genel fikir:
public static void MyParallelFor(int inclusiveLowerBound, int exclusiveUpperBound, Action<int> body)
{
// Get the number of processors, initialize the number of remaining
// threads, and set the starting point for the iteration.
int numProcs = Environment.ProcessorCount;
int remainingWorkItems = numProcs;
int nextIteration = inclusiveLowerBound;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
// Create each of the work items.
for (int p = 0; p < numProcs; p++)
{
ThreadPool.QueueUserWorkItem(delegate
{
int index;
while ((index = Interlocked.Increment(ref nextIteration) - 1) < exclusiveUpperBound)
body(index);
if (Interlocked.Decrement(ref remainingWorkItems) == 0)
mre.Set();
});
}
// Wait for all threads to complete.
mre.WaitOne();
}
}
Parallel.For tamamlanan döngü ayrıntıları içerir ParallelLoopResult değer türünü döndürür. aşağıdaki gibi onun aşırı biri:
public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);
paralel yürütme her zaman seri yürütme daha hızlı olmadığını fark etmek önemlidir. Paralel kullanılıp kullanılmayacağına karar vermek için, bir döngünün yinelemesi başına yapacağı iş yükünü tahmin etmelisiniz. Döngü tarafından gerçekte gerçekleştirilen iş, iplik senkronizasyon maliyetine nispeten küçükse, sıradan döngü kullanmak daha iyidir. döngü performansı için seri daha hızlı olduğu paralel olduğunda
Bu örnek birisidir:
static void Main(string[] args)
{
Action<int> action = new Action<int>(SimpleMethod);
// ordinary For loop performance estimation
var sw = Stopwatch.StartNew();
for(int i = 0; i < 1000; i++)
action(i);
Console.WriteLine("{0} sec.", sw.Elapsed.TotalSeconds);
// parallel For loop performance estimation
sw = Stopwatch.StartNew();
Parallel.For(0, 1000, action);
Console.WriteLine("{0} sec.", sw.Elapsed.TotalSeconds);
}
static void SimpleMethod(int index)
{
int d = 1;
int result = index/d;
}
Çıktı: İşte
0.0001963 sec.
0.0346729 sec.
Bu konuyu "kapsayan Microsoft'tan gerçekten iyi ücretsiz e-kitap [Paralel Programlama Desteği: .NET Framework 4 ile Paralel Kalıpları Anlama ve Uygulama] (https://www.microsoft.com/en-us/download/details.aspx?id=19222) " –