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

Parallel.For

In this page:

  1. Parallel.For

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}");
    }
}
🔒

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.