multiple parallel async calls with await

血红的双手。 提交于 2019-11-28 17:48:25
Stephen Cleary

The async/await includes a few operators to help with parallel composition, such as WhenAll and WhenAny.

var taskA = someCall(); // Note: no await
var taskB = anotherCall(); // Note: no await

// Wait for both tasks to complete.
await Task.WhenAll(taskA, taskB);

// Retrieve the results.
var resultA = taskA.Result;
var resultB = taskB.Result;

The simplest way is probably to do this:

var taskA = someCall();
var taskB = someOtherCall();
await taskA;
await taskB;

This is especially nice if you want the result values:

var result = await taskA + await taskB;

so you don't need to do taskA.Result.

TaskEx.WhenAll might be faster than two awaits after each other. i don't know since I haven't done performance investigation on that, but unless you see a problem I think the two consecutive awaits reads better, especially if you ewant the result values.

myaseedk

The Async CTP is no longer needed provided you're using .NET 4.5. Note that the async functionality is implemented by the compiler so .NET 4 apps can use it but VS2012 is required to compile it.

TaskEx is not needed anymore. The CTP couldn't modify the existing framework so it used extensions to accomplish things that the language would handle in 5.0. Just use Task directly.

So herewith, I have re-written the code(answered by Stephen Cleary) by replacing TaskEx with Task.

var taskA = someCall(); // Note: no await
var taskB = anotherCall(); // Note: no await

// Wait for both tasks to complete.
await Task.WhenAll(taskA, taskB);

// Retrieve the results.
var resultA = taskA.Result;
var resultB = taskB.Result;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!