Run Multiple Tasks In Parallel In C# 11

Munib ButtSenior .NET/Azure Developer/Analyst Consultant
CERTIFIED EXPERT
Senior technical systems architect/ analyst and developer/mentor with over 30 years’ experience (20+ years in Canada)
Published:
Today, we will see how we can run multiple tasks in parallel and collect the results once done in C# 11. This technique can help us use the multi-processors we have on our hardware and improve performance and efficiency of our applications.

Creating the project and code 

I will be creating this application using Visual Studio 2022 Community edition. Please follow the below steps:
 

1. Create a new console application in .NET core.
2. Name the project "ParallelTasksAndResults" and the solution "ParallelTasksAndResultsSol".
3. Select .NET 7 as the target framework.

Once the project is created, add the below four classes:


namespace ParallelTasksAndResults
{
    internal class ResultsData
    {
        public string? SearchType  { get; set; }
        public int NumberOfResults { get; set; }
 
    }
}
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ParallelTasksAndResults
{
    internal abstract class CollectData
    {
        public abstract Task<ResultsData> CollectDataAsync();
    }
}
 
 
namespace ParallelTasksAndResults
{
    internal class CollectDataA : CollectData
    {
        public override async Task<ResultsData> CollectDataAsync()
        {
            await Task.Delay(1000);
            return new ResultsData
            {
                 SearchType = "A",
                 NumberOfResults = 100
            };
        }
    }
}
 
namespace ParallelTasksAndResults
{
    internal class CollectDataB : CollectData
    {
        public override async Task<ResultsData> CollectDataAsync()
        {
            await Task.Delay(1000);
            return new ResultsData
            {
                 SearchType = "B",
                 NumberOfResults = 200
            };
        }
    }
}

The application now looks as below:


Finally, add the below code in the “Program.cs” file.

using ParallelTasksAndResults;
 
List<Task<ResultsData>> tasks = new List<Task<ResultsData>>();
 
tasks.Add(new CollectDataA().CollectDataAsync());
tasks.Add(new CollectDataB().CollectDataAsync());
 
ResultsData[] results = await Task.WhenAll(tasks);
 
foreach (ResultsData result in results)
{
     Console.WriteLine($"Search Type: {result.SearchType}, Number of Results: {result.NumberOfResults}");
}

The application is quite simple. We have a return type “ResultsData”. We create a list of tasks which return this type. We than add the two implementations of “CollectData” which are “CollectDataA” and “CollectDataB”. Both these classes have a function which return the “ResultsData” type. These are added to the list of Tasks. Then, we run the main command. This is “Task.WhenAll”. This runs both functions in parallel and returns the results in a “ResultsData” array. We than display these results on the console.


The code is available at the below location:

https://github.com/munibrbutt/articles-code/tree/main/Run%20Parallel%20Tasks%20and%20Collect%20Results/ParallelTasksAndResultsSol

Summary
 

 In today’s article, we looked at how we can run multiple tasks in parallel in C# 11. This technique allows us to utilize the multi cores we have on our hardware and hence make our applications run faster and be more responsive. The example explained above is quite simple, but the same logic can be applied for more complex scenarios.


0
1,388 Views
Munib ButtSenior .NET/Azure Developer/Analyst Consultant
CERTIFIED EXPERT
Senior technical systems architect/ analyst and developer/mentor with over 30 years’ experience (20+ years in Canada)

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.