C# Parallel.ForEach Tutorial | Parallel.ForEach Example C#
Hey buddy, do you want to speed up loops? 🚀
Imagine you have 100 packages 📦 to deliver. If one person delivers them one by one, it takes forever! But what if five delivery guys deliver five packages at the same time? Boom! Much faster, right?
That’s exactly what Parallel.ForEach does in C#! It helps you process lists and collections in parallel, making your program way faster. 🚀
What You Are Going to Learn in This Lesson
✔️ What Parallel.ForEach is and how it works.
✔️ A real-world example to understand it better.
✔️ The syntax of Parallel.ForEach.
✔️ A few simple C# programs using Parallel.ForEach with output.
✔️ When and why you should use it.
✔️ The C# version that introduced Parallel.ForEach.
What is Parallel.ForEach in C#?
Parallel.ForEach
is just like a foreach loop, but it runs iterations in parallel on multiple CPU cores. That means faster execution! 🚀
🔹 Introduced in: .NET Framework 4.0 (C# 4.0)
🔹 Namespace Required: System.Threading.Tasks
Syntax of Parallel.ForEach
Here’s the basic syntax:
Parallel.ForEach(collection, (item) =>
{
// Code to execute in parallel
});
🔹 collection
: The list, array, or collection to process.
🔹 item
: The current element being processed in parallel.
Parallel.ForEach Example C# (Super Simple!)
Let’s start with two easy examples before moving to a real-world example.
1️⃣ Simple Example: Print Items Faster
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static void Main()
{
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry", "Mango", "Orange" };
Parallel.ForEach(fruits, fruit =>
{
Console.WriteLine($"Processing: {fruit}");
});
}
}
Possible Output:
Processing: Mango
Processing: Apple
Processing: Orange
Processing: Cherry
Processing: Banana
Notice that the order is random? 🤯 That’s because multiple threads run at the same time!
2️⃣ Parallel.ForEach vs Normal ForEach (Speed Test!)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Stopwatch sw = new Stopwatch();
// Normal ForEach Loop
sw.Start();
foreach (var num in numbers)
{
Console.WriteLine($"Processing {num}...");
Thread.Sleep(500); // Simulate work
}
sw.Stop();
Console.WriteLine($"Normal ForEach Time: {sw.ElapsedMilliseconds} ms\n");
// Parallel.ForEach Loop
sw.Restart();
Parallel.ForEach(numbers, num =>
{
Console.WriteLine($"Processing {num}...");
Thread.Sleep(500); // Simulate work
});
sw.Stop();
Console.WriteLine($"Parallel.ForEach Time: {sw.ElapsedMilliseconds} ms");
}
}
Possible Output:
Processing 1...
Processing 2...
Processing 3...
Processing 4...
Processing 5...
Normal ForEach Time: 2500 ms
Processing 3...
Processing 1...
Processing 5...
Processing 2...
Processing 4...
Parallel.ForEach Time: 1000 ms
Parallel.ForEach finishes in ~1000 ms instead of 2500 ms! That’s way faster! 🚀
3️⃣ Real-World Example: Resizing Multiple Images in Parallel
Imagine you have 5 images 🖼️ and need to resize them quickly. Instead of resizing them one by one, let’s resize them in parallel!
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
List<string> images = new List<string> { "Image1.jpg", "Image2.jpg", "Image3.jpg", "Image4.jpg", "Image5.jpg" };
Parallel.ForEach(images, image =>
{
Console.WriteLine($"Resizing {image} started...");
Thread.Sleep(2000); // Simulate resizing
Console.WriteLine($"Resizing {image} completed!");
});
Console.WriteLine("All images resized!");
}
}
Possible Output:
Resizing Image3.jpg started...
Resizing Image1.jpg started...
Resizing Image4.jpg started...
Resizing Image2.jpg started...
Resizing Image5.jpg started...
Resizing Image3.jpg completed!
Resizing Image1.jpg completed!
Resizing Image4.jpg completed!
Resizing Image2.jpg completed!
Resizing Image5.jpg completed!
All images resized!
✅ All images process at the same time! That’s much faster than processing them one by one. 🚀
When Should You Use Parallel.ForEach?
🟢 Use Parallel.ForEach when:
✅ You have a list or collection to process.
✅ Each task does not depend on another.
✅ You need to speed up execution using multiple CPU cores.
🔴 Avoid it when:
❌ The collection is too small (Parallel overhead may slow things down).
❌ Order matters (Parallel execution does not maintain order).
❌ The task involves UI updates (UI updates should be done on the main thread).
Conclusion
So, buddy, now you know how Parallel.ForEach can make your code super fast! 🚀 If your program has a list of tasks, you can process them all at once instead of waiting for one by one execution. That’s a huge performance boost! 🎉
If you still have doubts, drop a comment below. We’d love to help! 😊
Next What?
Guess what? C# has something called Goto Loop that lets you jump to a specific part of your code. Sounds crazy, right? In the next chapter, you’ll learn about Goto Loop in C# and when to use (or avoid) it! Stay tuned! 🚀