本文介绍了在所有任务结束后,如何运行许多任务并获得结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I obtain result(bool) of those Tasks?

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;
}

推荐答案

您也可以使 Main()方法 async 并使用 WhenAll 而不是 WaitAll .并且在将 Task 分配给数组项时仅使用 T(),就不需要像 new Task(async()=>等待T());

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();
}

这篇关于在所有任务结束后,如何运行许多任务并获得结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 16:48