Running Tasks In Parallel

Introduction

Today we will see how we can run different tasks in parallel in C#. With the current hardware strength, we have machines with multiple processors. Hence, we certainly have the ability to utilize these and run our tasks in parallel to improve performance. But are we really doing this. Let us look at some sample code, which will let us do this. This can serve as a framework on which this methodology can be enhanced.

Creating the solution and adding the code

Let us create a C# console application in Visual Studio 2022 Community edition. Once created, add the below code.

Running Tasks in Parallel

// Create a generic list to hold all our tasks
var allTasks = new List < Task > ();
// Add your tasks to this generic list
// Here we simply add the same task with different input parameters
for (var i = 0; i <= 10; i++) {
    allTasks.Add(RunTaskAsync(i));
}
// Run all tasks in parallel and wait for results from all
await Task.WhenAll(allTasks);
// Collect return values from all tasks which have now executed
var returnValues = new List < int > ();
foreach(var task in allTasks) {
    var returnValue = ((Task < int > ) task).Result;
    returnValues.Add(returnValue);
}
// Display returned values on console
foreach(var returnValue in returnValues) {
    Console.WriteLine(returnValue);
}
// The task we want to run
async Task < int > RunTaskAsync(int val) {
    return await Task.FromResult(val * val);
}

Here you see that we simply create a list of tasks and run them in parallel using the Task.WhenAll method. Then, we collect the results and handle them accordingly.

Running Tasks in Parallel

Summary

In this article, we looked at how we can execute tasks in parallel in .NET 6. I created a simple framework where we define the tasks and then run them after adding to a generic list. Once completed, we extract the results, and these can be used as required.


Similar Articles