Parallel.For
Parallel.For splits a loop's turns across several workers at once, like a group of friends each cleaning a different room. It can finish big jobs faster.
In this page:
Syntax
Parallel.For(start, endExclusive, i =>
{
// body runs concurrently for each i
});
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Updating a shared variable with
total += iinsideParallel.For, which is a race condition; useInterlocked.Addor alock. - Assuming the iterations run in order, when they run on several threads so results such as printed lines come out in any order.
- Expecting the end value to be included, when
Parallel.For(1, 6, ...)runs 1 to 5 because the upper bound is exclusive.
Chapter Summary
asyncandawaitlet code wait for work without blocking.TaskandTask<T>represent asynchronous operations.ConfigureAwait,CancellationToken, andParallel.Forcontrol and cancel asynchronous and parallel work.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: