High-Performance .NET: Async, Multithreading, and Parallel Programming Parallel Loops in .NET Created: 19 Jan 2026 Updated: 19 Jan 2026

Parallel.Foreach

In high-performance application development, processing large collections of data efficiently is a common challenge. While a standard foreach loop processes items one by one on a single thread, Parallel.ForEach allows developers to distribute these tasks across multiple CPU cores.

By leveraging the Task Parallel Library (TPL), Parallel.ForEach optimizes throughput for object-based collections, making it an essential tool for modern software engineering.

How Parallel.ForEach Works

The Parallel.ForEach method is designed for collections that implement IEnumerable<T>. It takes the collection and an Action<T> delegate, executing the action for each item in parallel.

Partitioning Strategy

The efficiency of this method comes from its ability to "partition" data:

  1. Direct Indexing: If the source is an Array or a List, the framework uses direct indexing to split the work into chunks immediately.
  2. Partitioner Instance: For other enumerations, a Partitioner determines the optimal way to divide the items among available threads to prevent any single thread from becoming a bottleneck.

Comparison: Parallel.For vs. Parallel.ForEach

While both methods provide parallelism, they serve different data structures:

AspectParallel.For()Parallel.ForEach()
Input TypeA numeric range (e.g., 0 to 1,000)A collection (Array, List, IEnumerable<T>)
Loop VariableThe numeric index (int or long)Individual collection item (T)
Primary UseNumeric data & matrix processingProcessing objects and data structures

Key Scenarios for Parallel.ForEach

Parallel.ForEach is optimized for processing arrays, lists, and other enumerations. Below are the most common real-world use cases:

Use CaseDescription
Large Data SetsParsing or analyzing data in databases, CSV files, JSON, or other large data files.
Web ScrapingScraping data from multiple websites or APIs simultaneously to minimize wait times.
Bulk Email/NotificationsSending bulk communications to a large number of recipients concurrently.
Data TransformationConverting, mapping, or encrypting data within a large collection.
Data StreamingReal-time processing of continuous data streams in parallel.
Machine Learning & AIExecuting tasks like feature extraction, data augmentation, or batch inference.
Bulk Network OperationsDownloading or uploading multiple files simultaneously.
Bulk File ProcessingProcessing entire directories of files (e.g., resizing images or indexing text).


Example

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class PriceProcessor
{
public void CalculateTaxes(List<double> prices)
{
const double TaxRate = 0.18;

// Parallel.ForEach takes the list and the action to perform
Parallel.ForEach(prices, price =>
{
// This logic runs in parallel for different prices
double finalPrice = price + (price * TaxRate);
Console.WriteLine($"Original: ${price} -> Final: ${finalPrice:F2} (Thread: {Environment.CurrentManagedThreadId})");
});
}
}
Share this lesson: