0
0
CsharpHow-ToBeginner · 3 min read

How to Use Parallel.For in C# for Simple Parallel Loops

Use Parallel.For in C# to run a loop where iterations execute in parallel on multiple threads. It takes a start index, an end index, and a loop body action, making it easy to speed up independent tasks without manual thread management.
📐

Syntax

The Parallel.For method runs a loop in parallel. It requires three main parts:

  • startInclusive: The first index to start looping from.
  • endExclusive: The index to stop before (not included).
  • body: A delegate (action) that defines what to do for each index.

This method automatically manages threads to run iterations concurrently.

csharp
Parallel.For(int startInclusive, int endExclusive, Action<int> body);
💻

Example

This example shows how to use Parallel.For to print numbers from 0 to 9 in parallel. The order may vary because iterations run on different threads.

csharp
using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Parallel.For(0, 10, i =>
        {
            Console.WriteLine($"Processing number {i} on thread {System.Threading.Thread.CurrentThread.ManagedThreadId}");
        });
    }
}
Output
Processing number 0 on thread 4 Processing number 1 on thread 5 Processing number 2 on thread 6 Processing number 3 on thread 4 Processing number 4 on thread 5 Processing number 5 on thread 6 Processing number 6 on thread 4 Processing number 7 on thread 5 Processing number 8 on thread 6 Processing number 9 on thread 4
⚠️

Common Pitfalls

Common mistakes when using Parallel.For include:

  • Modifying shared variables without synchronization, causing data races.
  • Assuming the loop runs in order; iterations run concurrently and order is not guaranteed.
  • Using Parallel.For for very small or quick tasks, which can add overhead and slow down performance.

Always ensure thread safety when accessing shared data.

csharp
using System;
using System.Threading.Tasks;

class Program
{
    static int total = 0;

    static void Main()
    {
        // Wrong: modifying shared variable without lock
        Parallel.For(0, 1000, i =>
        {
            total += i; // This can cause wrong results
        });
        Console.WriteLine($"Wrong total: {total}");

        // Right: use lock to protect shared variable
        total = 0;
        object lockObj = new object();
        Parallel.For(0, 1000, i =>
        {
            lock (lockObj)
            {
                total += i;
            }
        });
        Console.WriteLine($"Correct total: {total}");
    }
}
Output
Wrong total: 123456 Correct total: 499500
📊

Quick Reference

Parallel.For Cheat Sheet:

  • startInclusive: loop start index (inclusive)
  • endExclusive: loop end index (exclusive)
  • body: action to run for each index
  • Runs iterations in parallel on multiple threads
  • Order of execution is not guaranteed
  • Use synchronization for shared data

Key Takeaways

Parallel.For runs loop iterations concurrently to speed up independent tasks.
Always protect shared data with locks or thread-safe methods inside Parallel.For.
The loop order is not guaranteed; do not rely on sequential execution.
Use Parallel.For for CPU-bound tasks that benefit from parallelism.
Avoid Parallel.For overhead for very small or quick loops.