同时运行多个等待 [英] Run multiple await at the same time

查看:56
本文介绍了同时运行多个等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的代码:

I have a code that looks something like this:

firstList = await GetFirstListFilesAsync();
textBlock1.Text = "found " + firstList.Count + " first list's results";
secondList = await GetSecondListFilesAsync();
textBlock2.Text = "found " + secondList.Count + " second list's results";
thirdList = await GetThirdListFilesAsync();
textBlock3.Text = "found " + thirdList.Count + " third list's results"

因此,现在它获取第一个列表,设置第一个 TextBlock 文本,然后获取第二个列表,设置第二个 TextBlock 文本,然后获取第三个列表,并设置第三个TextBlock 文本.但是我希望所有等待操作都可以同时运行,因此所有 TextBlock 都将或多或少地同时更新.或可能不会同时出现-每个 TextBlock 都将在相应的await方法完成时进行更新.无论如何,我想在这里实现的是更快地获得结果.如果我一一运行这些方法,它们会等到前一个方法完成,但是如果它们同时运行,则第三个方法会更快地返回结果,对吗?所以我的问题是-可能吗?如果是的话,怎么办?

So now it gets first list, sets first TextBlock text, then it gets second list, sets second TextBlock text and then gets third list and sets third TextBlock text. But I would like that all await operations would run simultaneously, so all TextBlocks would update more or less at the same time. Or maybe not at the same time - each TextBlock would update as the corresponding await method finishes. Anyway, what I want to achieve here, is to get results faster. if I run those methods one by one, they wait until the previous is finished, but if they would run all at the same time, third method would return the result faster, right? So my question is - is that possible? And if yes, then how?

推荐答案

我认为这是您要寻找的:

I think this is what you are looking for:

var tasks = new Task<MyMethodReturnObject>[3];
tasks[0] = GetFirstListFilesAsync();
tasks[1] = GetSecondListFilesAsync();
tasks[2] = GetThirdListFilesAsync();

// At this point, all three tasks are running at the same time.

// Now, we await them all.
await Task.WhenAll(tasks);

// Get an individual result, where result is MyMethodReturnObject
var myText = tasks[0].Result;

// Loop through results
var results = tasks.Select(o => o.Result).ToList();
foreach (var result in results)
{
    Console.Write(result);
}

来源: http://blog.stephencleary.com/2012/02/async-and-await.html

这篇关于同时运行多个等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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