温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How to run many tasks and get their result after all of them ended?
async-await asynchronous c# task

c# - 所有任务结束后,如何运行许多任务并获得结果?

发布于 2020-04-20 14:45:50

我如何获得这些任务的结果(布尔)?

public static Random rnd = new Random();

static void Main()
{
    var tasks = new Task[10];

    for (int i = 0; i < 10; i++)
    {
        tasks[i] = new Task(async () => await T());
    }

    Task.WaitAll(tasks);

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

    Console.ReadKey();
}

public static async Task<bool> T()
{
    await Task.Delay(500);
    return rnd.Next(2) == 1 ? true : false;
}

查看更多

提问者
Joelty
被浏览
56
Pavel Anikhouski 2020-02-14 17:30

您也可以制作Main()方法async并使用WhenAll代替WaitAll并且只T()在分配Task给数组项使用,所以不需要这样做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();
}