Creating the project and code
I will be creating this application using Visual Studio 2022 Community edition. Please follow the below steps: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
};
}
}
}
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/ParallelTasksAndResultsSolSummary
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.
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.
Comments (0)