JavaRush /Courses /C# SELF /Parallel data processing

Parallel data processing

C# SELF
Level 60, Lesson 3
Available

1. Introduction

Today we'll go over how to process large amounts of data as fast as possible by using all available CPU cores on your machine (or server). For that we'll use classes from the System.Threading.Tasks.Parallel namespace, namely the Parallel.For and Parallel.ForEach methods.

What if the task is pure CPU-bound?

A classic for or foreach loop processes elements one after another. Simple and reliable. But on a multicore CPU the loop uses only one core while the others are just idle. Why not split the array into chunks and process them on different cores simultaneously?

Example:


// We'll compute the sum of squares from 1 to N
long sum = 0;
for (int i = 1; i <= 1_000_000; i++)
{
    sum += i * i;
}

This code is simple but runs sequentially. What if we scatter the work across cores?

Meet the Family: Parallel.For and Parallel.ForEach

What are they?

  • Parallel.For — works like a normal for loop but splits the work into chunks and automatically schedules them across threads, using all available cores.
  • Parallel.ForEach — processes a collection like a normal foreach, but in parallel.

Official docs:

Why is this handy?

You don't have to create, start, and manage threads manually. The framework does the heavy lifting. You write code similar to a regular loop, and parallelism happens under the hood.

2. Syntax: basic examples

Parallel.For


long total = 0;
Parallel.For(1, 1_000_001, i =>
{
    // This lambda may be executed concurrently by different threads
    Interlocked.Add(ref total, i * i); // To avoid races
});
Console.WriteLine($"Sum of squares: {total}");

Note: we update the total variable via Interlocked.Add to avoid data races.

Parallel.ForEach


var numbers = Enumerable.Range(1, 10_000_000).ToArray();
long sum = 0;

Parallel.ForEach(numbers, num =>
{
    Interlocked.Add(ref sum, num * num); // Safe addition
});
Console.WriteLine($"Sum of squares: {sum}");

Inside view (visual diagram)


+-------------------+
|Collection/range   |
+---------+---------+
          |
          v
  +----------------------+
  |   Parallel.ForEach   |
  +----------+-----------+
             |
        +----+----+----+----+
        |         |         |
        v         v         v
  Task #1    Task #2    Task #3   ... (available cores)
        |         |         |
     +--+----+  +--+-----+  +--+-----+
     |Process |  |Process |  |Process |
     +-------+  +--------+  +--------+
        \         |         /
         +--------+--------+
                  |
                  v
             Result

3. Processing large files (CPU-bound processing)

Suppose we have a text file with tens of thousands of lines — for example, each line contains a number. We need to read the file, square each number and compute the sum of squares.

Synchronous version


string[] lines = File.ReadAllLines("numbers.txt");
long sum = 0;

foreach (var line in lines)
{
    if (long.TryParse(line, out long n))
    {
        sum += n * n;
    }
}
Console.WriteLine($"Sum of squares: {sum}");

Parallel version with Parallel.For


string[] lines = File.ReadAllLines("numbers.txt");
long sum = 0;

Parallel.For(0, lines.Length, i =>
{
    if (long.TryParse(lines[i], out long n))
    {
        Interlocked.Add(ref sum, n * n);
    }
});
Console.WriteLine($"Sum of squares: {sum}");

What's changed: we replaced the regular loop with a parallel one, and now sum is incremented via Interlocked.Add to avoid thread conflicts.

4. What happens under the hood?

When you call Parallel.For or Parallel.ForEach, .NET automatically splits your work into chunks and schedules them across available processor cores using the thread pool. Each chunk is processed independently on its own thread.

Benefit: if you have 4 cores, work can run almost 4x faster (assuming the task doesn't depend on external resources or hit other limits like memory or disk throughput).

Comparing execution time


var numbers = Enumerable.Range(1, 100_000_000).ToArray();
long sumSync = 0;
var sw = System.Diagnostics.Stopwatch.StartNew();

foreach (var n in numbers)
    sumSync += n * n;

sw.Stop();
Console.WriteLine($"Sync: {sw.ElapsedMilliseconds} ms, sum: {sumSync}");

long sumParallel = 0;
sw.Restart();

Parallel.ForEach(numbers, n =>
    Interlocked.Add(ref sumParallel, n * n)
);

sw.Stop();
Console.WriteLine($"Parallel: {sw.ElapsedMilliseconds} ms, sum: {sumParallel}");

Try it yourself! On a powerful machine you may see significant speedups, but it all depends on the workload and bottlenecks.

5. Useful nuances

Controlling degree of parallelism

Sometimes it makes sense to limit the number of threads used (for example, to avoid overloading the system). Use MaxDegreeOfParallelism for that:


using System.Threading.Tasks;
long sum = 0;
var options = new ParallelOptions { 
    MaxDegreeOfParallelism = 2 
};
Parallel.For(0, 100, options, i =>
{
    Interlocked.Add(ref sum, i * i);
});
Console.WriteLine($"Sum of squares: {sum}");

When it's useful: if part of your work is heavy on disk rather than CPU — reduce the number of threads and measure the impact.

When to use parallel loops

Regular for Parallel.For/Parallel.ForEach
Processors Uses one core Uses all cores
Order Guaranteed Not guaranteed
Speed Usually slower Often significantly faster
Simplicity Very simple Requires thread-safety considerations
Best fit Small datasets, I/O-bound Large datasets, CPU-bound

Extension: what else can Parallel do?

Parallel.Invoke() — runs several independent methods at the same time:


static void DoTask1() => Console.WriteLine("Task 1 completed");
static void DoTask2() => Console.WriteLine("Task 2 completed");
static void DoTask3() => Console.WriteLine("Task 3 completed");

Parallel.Invoke(
    () => DoTask1(),
    () => DoTask2(),
    () => DoTask3()
);

Each method will run on its own core if possible.

Real-world uses

  • Image processing: process different tiles concurrently (e.g. apply a filter).
  • Array computations: financial calculations, simulations (portfolio evaluation across scenarios).
  • Working with large log files: searching and aggregating across multiple cores.
  • Machine learning: splitting work into independent tasks (data batches, feature engineering).

And of course, in interviews you can not only explain what parallel loops are, but also honestly discuss their pros and cons.

6. Common mistakes when using Parallel.For and Parallel.ForEach

Mistake #1: Ignoring data races.
Updating a shared variable without Interlocked or a lock leads to incorrect results because of concurrent access.

Mistake #2: Using them for I/O-bound tasks.
Parallel loops don't speed up disk- or network-bound tasks and may even slow them down due to overhead.

Mistake #3: Assuming processing order.
Parallel loops don't guarantee the order of element processing, which can break logic that depends on sequence.

Mistake #4: Ignoring side effects.
Mutating shared state (e.g. collections) inside parallel loops can cause errors unless you use thread-safe structures.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION