的异步方法并发执行 [英] Concurrent execution of async methods

查看:153
本文介绍了的异步方法并发执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用异步/伺机模式,我有向Web服务3个不同的呼叫,然后返回结果的结合的方法。

  VAR RESULT1 =等待myService.GetData(源1);
VAR结果2 =等待myService.GetData(源2);
VAR result3 =等待myService.GetData(source3);allResults =联盟(RESULT1,结果2,result3);

使用典型的await,这3个通话将执行同步WRT对方。我怎么会去让他们并发执行,并加入结果​​他们完成?


解决方案

  我

怎么会去让它们并行执行,并加入结果​​他们完成?


简单的办法就是创建所有任务,然后等待着他们:

  VAR任务1 = myService.GetData(源1);
VAR TASK2 = myService.GetData(源2);
VAR TASK3 = myService.GetData(source3);//现在一切都开始了,我们可以等待他们
VAR RESULT1 =等待独立写作;
VAR RESULT1 =等待TASK2;
VAR RESULT1 =等待TASK3;

您也可以考虑<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall%28v=vs.110%29.aspx\"><$c$c>Task.WhenAll.你需要考虑,一个以上的任务将失败......上述code,你不会看到 TASK3 的失败,例如,如果<可能性code> TASK2 失败 - 因为你的异步方法将传播从 TASK2 你等待前 TASK3

我不是在这里提示一个特定的策略,因为这将取决于您的具体情况。你可能只在乎成功/失败和记录的有一个的故障原因,在这种情况下,上述code是罚款。否则,你可能附加延续原来的任务日志的所有的例外,例如

Using the async/await model, I have a method which makes 3 different calls to a web service and then returns the union of the results.

var result1 = await myService.GetData(source1);
var result2 = await myService.GetData(source2);
var result3 = await myService.GetData(source3);

allResults = Union(result1, result2, result3);

Using typical await, these 3 calls will execute synchronously wrt each other. How would I go about letting them execute concurrently and join the results as they complete?

解决方案

How would I go about letting them execute in parallel and join the results as they complete?

The simplest approach is just to create all the tasks and then await them:

var task1 = myService.GetData(source1);
var task2 = myService.GetData(source2);
var task3 = myService.GetData(source3);

// Now everything's started, we can await them
var result1 = await task1;
var result1 = await task2;
var result1 = await task3;

You might also consider Task.WhenAll. You need to consider the possibility that more than one task will fail... with the above code you wouldn't observe the failure of task3 for example, if task2 fails - because your async method will propagate the exception from task2 before you await task3.

I'm not suggesting a particular strategy here, because it will depend on your exact scenario. You may only care about success/failure and logging one cause of failure, in which case the above code is fine. Otherwise, you could potentially attach continuations to the original tasks to log all exceptions, for example.

这篇关于的异步方法并发执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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