从Task.WhenAll获取返回值 [英] Getting return values from Task.WhenAll

查看:196
本文介绍了从Task.WhenAll获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这里是一个相当简单的.我有一个对象集合,每个对象都有一个我要调用并从中收集值的异步方法.我希望它们并行运行.我想实现的目标可以总结为一条虚线代码:

Hopefully a fairly simple one here. I have a collection of objects, each of which has an async method that I want to call and collect values from. I'd like them to run in parallel. What I'd like to achieve can be summed up in one broken line of code:

IEnumerable<TestResult> results = await Task.WhenAll(myCollection.Select(v => v.TestAsync()));

我尝试了各种写此方法的方法,但均未成功.有什么想法吗?

I've tried various ways of writing this without success. Any thoughts?

推荐答案

如果您正在等待的任务具有相同类型的结果,则 Task.WhenAll 返回它们的数组.例如此类:

If the tasks you're awaiting have a result of the same type Task.WhenAll returns an array of them. For example for this class:

public class Test
{
    public async Task<TestResult> TestAsync()
    {
        await Task.Delay(1000); // Imagine an I/O operation.
        return new TestResult();
    }
}

我们得到以下结果:

var myCollection = new List<Test>();
myCollection.Add(new Test());

IEnumerable<TestResult> results = await Task.WhenAll(myCollection.Select(v => v.TestAsync()));

这篇关于从Task.WhenAll获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆