Complete C# Tutorial

C# Parallel.For Tutorial | Easy Parallel.For Example C#

Hey buddy, ever wished loops could run faster? ๐Ÿš€

Imagine youโ€™re baking 10 pizzas ๐Ÿ•. If you bake them one by one, it takes a long time. But what if you use five ovens and bake five pizzas at once? Much faster, right?

Thatโ€™s exactly how Parallel.For works in C#! Instead of executing tasks sequentially, it splits them across multiple CPU cores, making your program run much faster.

What is Parallel.For in C#?

The Parallel.For loop is a multi-threaded version of the normal for loop. It allows multiple iterations to run at the same time, making execution faster.

๐Ÿ”น Introduced in: .NET Framework 4.0 (C# 4.0)
๐Ÿ”น Namespace Required: System.Threading.Tasks

Syntax of Parallel.For

Hereโ€™s how Parallel.For works:

				
					Parallel.For(startIndex, endIndex, (index) =>
{
    // Code to execute in parallel
});
				
			
  1. startIndex: The loop starting point (like 0).\
  2. endIndex: The loop stopping condition (endIndex - 1).
  3. index: The loop variable for each iteration.

Parallel.For Example C# (Easy One First!)

Letโ€™s compare a normal for loop with a Parallel.For loop.

๐Ÿ‘Ž Normal For Loop (Slow)

				
					using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine($"Task {i} running...");
            System.Threading.Thread.Sleep(500); // Simulate work
        }

        sw.Stop();
        Console.WriteLine($"Time taken: {sw.ElapsedMilliseconds} ms");
    }
}
				
			

Output (Normal For Loop)

				
					Task 0 running...
Task 1 running...
Task 2 running...
...
Task 9 running...
Time taken: 5000 ms (approx.)
				
			

๐Ÿ’ก Each iteration runs one after another, making it slow.

๐Ÿš€ Parallel.For Loop (Faster Execution!)

				
					using System;
using System.Diagnostics;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        Parallel.For(0, 10, i =>
        {
            Console.WriteLine($"Task {i} running...");
            System.Threading.Thread.Sleep(500); // Simulate work
        });

        sw.Stop();
        Console.WriteLine($"Time taken: {sw.ElapsedMilliseconds} ms");
    }
}
				
			

Output (Parallel.For Loop)

				
					Task 3 running...
Task 7 running...
Task 1 running...
Task 6 running...
Task 2 running...
...
Time taken: 1000 - 1500 ms (approx.)
				
			

๐Ÿ’ก Notice how tasks run at the same time? The total time is much shorter because multiple iterations execute concurrently! ๐Ÿš€

๐Ÿ’ก When Should You Use Parallel.For?

๐ŸŸข Use Parallel.For when:

โœ… You have tasks that take longer to process.
โœ… The iterations donโ€™t depend on each other.
โœ… You want to speed up execution using multiple CPU cores.

๐Ÿ”ด Avoid it when:

โŒ The workload is small (Parallel overhead makes it slower).
โŒ Iterations must run in sequence (like calculations with dependencies).
โŒ It involves UI updates (UI updates should be done on the main thread).

Parallel.For Example C# (Super Simple!)

Letโ€™s start with two easy examples before moving to a real-world example.

1๏ธโƒฃ Simple Example: Print Numbers Faster

				
					using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Parallel.For(1, 6, i =>
        {
            Console.WriteLine($"Task {i} running...");
        });
    }
}
				
			

Possible Output:

				
					Task 3 running...
Task 1 running...
Task 4 running...
Task 2 running...
Task 5 running...
				
			

See the magic? ๐Ÿ˜ฒ The numbers donโ€™t print in order because multiple threads execute at the same time!

2๏ธโƒฃ Parallel.For vs Normal For Loop (Speed Test!)

				
					using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Stopwatch sw = new Stopwatch();

        // Normal For Loop
        sw.Start();
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Processing task {i}...");
            Thread.Sleep(500); // Simulate work
        }
        sw.Stop();
        Console.WriteLine($"Normal For Loop Time: {sw.ElapsedMilliseconds} ms\n");

        // Parallel.For Loop
        sw.Restart();
        Parallel.For(1, 6, i =>
        {
            Console.WriteLine($"Processing task {i}...");
            Thread.Sleep(500); // Simulate work
        });
        sw.Stop();
        Console.WriteLine($"Parallel.For Time: {sw.ElapsedMilliseconds} ms");
    }
}
				
			

Possible Output:

				
					Processing task 1...
Processing task 2...
Processing task 3...
Processing task 4...
Processing task 5...
Normal For Loop Time: 2500 ms

Processing task 3...
Processing task 1...
Processing task 5...
Processing task 2...
Processing task 4...
Parallel.For Time: 1000 ms

				
			

๐Ÿ˜Ž Parallel.For completed in ~1000 ms instead of 2500 ms! Faster execution! ๐Ÿš€

3๏ธโƒฃ Real-World Example: Downloading Files in Parallel!

Imagine you are downloading five files from the internet. A normal loop downloads them one by one. But using Parallel.For, we can download all at the same time!

				
					using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        string[] files = { "File1", "File2", "File3", "File4", "File5" };

        Parallel.For(0, files.Length, i =>
        {
            Console.WriteLine($"Downloading {files[i]} started...");
            Thread.Sleep(2000); // Simulating download
            Console.WriteLine($"Downloading {files[i]} completed!");
        });

        Console.WriteLine("All downloads completed!");
    }
}
				
			

Possible Output:

				
					Downloading File3 started...
Downloading File1 started...
Downloading File4 started...
Downloading File2 started...
Downloading File5 started...
Downloading File3 completed!
Downloading File1 completed!
Downloading File4 completed!
Downloading File2 completed!
Downloading File5 completed!
All downloads completed!
				
			

โœ… All files download at the same time! Much faster than one by one. ๐Ÿš€

Conclusion

So, my friend, now you know how Parallel.For can speed things up! ๐ŸŽ‰ If your program has independent tasks, you can split the work across multiple CPU cores and get things done in a fraction of the time. ๐Ÿš€

If youโ€™re still unsure about anything, drop a comment below. Weโ€™d love to help! ๐Ÿ˜Š

Next What?

Guess what? Parallel.ForEach works just like Parallel.For, but for lists and collections! Sounds cool, right? In the next chapter, youโ€™ll learn about Parallel.ForEach in C# and how to process lists and arrays in parallel. Stay tuned! ๐Ÿš€

Leave a Comment

Share this Doc

Parallel.For

Or copy link