← Back to C# Course | Chapter 13: Async Programming | Lesson 6 of 6

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:

  1. Parallel.For
Syntax
csharp
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

markup
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}");
    }
}
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
  1. Updating a shared variable with total += i inside Parallel.For, which is a race condition; use Interlocked.Add or a lock.
  2. Assuming the iterations run in order, when they run on several threads so results such as printed lines come out in any order.
  3. Expecting the end value to be included, when Parallel.For(1, 6, ...) runs 1 to 5 because the upper bound is exclusive.
Chapter Summary
  • async and await let code wait for work without blocking.
  • Task and Task<T> represent asynchronous operations.
  • ConfigureAwait, CancellationToken, and Parallel.For control and cancel asynchronous and parallel work.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.