Parallel.For
In this page:
Parallel.For
Parallel.For runs loop iterations concurrently across multiple threads, useful for CPU-bound work where iterations don't depend on each other. It's a simpler alternative to manually managing threads for data-parallel tasks. Because iterations run out of order and concurrently, shared mutable state must be protected or avoided.
Warning: Do not increment a shared variable directly inside Parallel.For without synchronization — it causes race conditions.
Example: Parallel.For
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int total = 0;
Parallel.For(1, 6, i =>
{
Interlocked.Add(ref total, i);
});
Console.WriteLine($"Total: {total}");
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: