The Parallel class in the System.Threading.Tasks namespace provides powerful methods to run loops and actions concurrently. This guide explores its primary methods—For, ForEach, ForEachAsync, and Invoke—along with examples of their usage and key benefits.
Why Use the Parallel Class?
Multithreading enables applications to perform multiple operations simultaneously, maximizing CPU utilization and improving performance. The Parallel class simplifies this by providing high-level methods to handle concurrency effectively.
Core Methods of the Parallel Class
1. Parallel.For
The Parallel.For method is similar to a traditional for loop but executes iterations concurrently:
Parallel.For(0, 10, i => {
Console.WriteLine(i);
});
Output:
- Unlike a regular
forloop, the output order may vary because iterations run in parallel.
Overloads with ParallelOptions
You can control the behavior of Parallel.For using the ParallelOptions class:
var options = new ParallelOptions {
MaxDegreeOfParallelism = 2 // Limit to 2 concurrent tasks
};
Parallel.For(0, 10, options, i => {
Console.WriteLine(i);
});
2. Parallel.ForEach
The ForEach method operates on collections:
var items = new[] { "A", "B", "C", "D" };
Parallel.ForEach(items, item => {
Console.WriteLine(item);
});
Similar to Parallel.For, the output order may vary due to parallel execution.
3. Parallel.ForEachAsync
For asynchronous operations within a collection, use Parallel.ForEachAsync. This method handles asynchronous tasks efficiently:
var items = new[] { "A", "B", "C", "D" };
await Parallel.ForEachAsync(items, async (item, cancellationToken) => {
await Task.Delay(100); // Simulating async work
Console.WriteLine(item);
});
Key Features:
- Accepts a cancellation token for stopping execution.
- Returns a
Taskthat can be awaited.
4. Parallel.Invoke
The Invoke method allows you to run multiple independent actions concurrently:
Parallel.Invoke(
() => Console.WriteLine("Task 1"),
() => Console.WriteLine("Task 2"),
() => Console.WriteLine("Task 3")
);
Advantages:
- Useful for executing multiple independent actions without creating multiple tasks manually.
- Supports
ParallelOptionsfor fine-grained control.
Practical Scenarios for the Parallel Class
- Data Processing: Process large datasets in parallel to improve performance.
- Web Scraping: Execute multiple HTTP requests concurrently.
- Image Processing: Apply filters or transformations to images in a collection simultaneously.
- Parallel API Calls: Run independent API calls in parallel to save time.
Considerations
- Thread Safety: Ensure shared resources are accessed safely when using parallel methods.
- Degree of Parallelism: Limit concurrency with
ParallelOptionsto avoid overwhelming system resources. - Error Handling: Use try-catch blocks within parallel actions to handle exceptions.
- Cancellation: Use cancellation tokens to gracefully stop parallel tasks when required.
Conclusion
The Parallel class is a versatile tool for enhancing the performance of C# applications. Whether you’re iterating over collections, running asynchronous tasks, or executing independent methods, the Parallel class simplifies multithreading and improves efficiency. Experiment with the methods and tailor their usage to fit your application’s needs!
This complete exercise is available in the YouTube video link here: https://youtu.be/7gsqukU9Kr8?si=XKSBujfMHjyibNaP