[Solved] How to run many tasks and get their result after all of them ended?

Introduction

If you are looking for a way to run multiple tasks and get the results after all of them have ended, then you have come to the right place. In this article, we will discuss how to run many tasks and get their result after all of them have ended. We will discuss the different methods available to achieve this, such as using threads, asynchronous programming, and multiprocessing. We will also discuss the pros and cons of each method and provide some examples of how to use them. Finally, we will provide some tips and best practices for running multiple tasks and getting their results.

Solution

The best way to run many tasks and get their result after all of them ended is to use a thread pool. A thread pool is a collection of threads that can be used to execute multiple tasks concurrently. The thread pool will manage the threads and ensure that all tasks are completed before returning the results. Additionally, a thread pool can be used to optimize the performance of the tasks by allowing them to run in parallel.

You can make Main() method async as well and use WhenAll instead of WaitAll. And use just T() when assign Task to array item, there is no need to do it like that new Task(async () => await T());

static async Task Main()
{
    var tasks = new Task<bool>[10];

    for (int i = 0; i < 10; i++)
    {
        tasks[i] = T();
    }

    await Task.WhenAll(tasks);

    for (int i = 0; i < tasks.Length; i++)
    {
        Console.WriteLine($"Task {i} result = {tasks[i].Result}");
    }

    Console.ReadKey();
}

solved How to run many tasks and get their result after all of them ended?