c# - 同时运行多个等待

标签 c# asynchronous windows-8.1-universal

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

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 方法完成而更新。无论如何,我想在这里实现的是更快地获得结果。如果我一个一个地运行这些方法,它们会等到前一个方法完成,但如果它们同时运行,第三个方法会更快地返回结果,对吧?所以我的问题是——这可能吗?如果是,那么如何?

最佳答案

我想这就是您要找的:

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

关于c# - 同时运行多个等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36907549/

相关文章:

c# - 在共享的 WinRT 8.1 页面上显示广告

c# - 将参数传递给 COM 接口(interface)

c# - 与数组相比,使用 IEnumerable 有哪些优势?

javascript - 如何暂停 React-Autosuggest 搜索,直到异步数据准备就绪?

c# - Windows 8 - 如何正确获取嵌套文件夹?

windows-runtime - 控制后台任务实例

c# - 从 DTE 访问属性信息

c# - 指针按下 : left or right button?

http - 响应后异步工作

c# - 在 Windows 10 中检测到布局循环,但在 Windows 8.1 中未检测到