等待上一个完成的任务一样task.Result? [英] Await on a completed task same as task.Result?
问题描述
我目前正在读,在C#食谱并发由斯蒂芬·克利里,我注意到了以下技术:
I'm currently reading "Concurrency in C# Cookbook" by Stephen Cleary, and I noticed the following technique:
var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
if (completedTask == timeoutTask)
return null;
return await downloadTask;
的 downloadTask 的是httpclient.GetStringAsync一个电话,和 timeoutTask 的正在执行Task.Delay。
downloadTask is a call to httpclient.GetStringAsync, and timeoutTask is executing Task.Delay.
在的情况下,它没有超时,那么downloadTask已经完成。为什么因为任务已经完成,需要做第二次的await而不是返回downloadTask.Result的,?
In the event that it didn't timeout, then downloadTask is already completed. Why is necessary to do a second await instead of returning downloadTask.Result, given that the task is already completed?
推荐答案
目前已经有一些很好的答案/评论在这里,但只是为了附和...
There are already some good answers/comments here, but just to chime in...
有两个原因我preFER 等待
在结果
(或等待
)。首先,错误处理是不同的; 等待
不换行除外在 AggregateException
。理想情况下,异步code不应该有应对 AggregateException
可言,除非它专门的希望的到。
There are two reasons why I prefer await
over Result
(or Wait
). The first is that the error handling is different; await
does not wrap the exception in an AggregateException
. Ideally, asynchronous code should never have to deal with AggregateException
at all, unless it specifically wants to.
第二个原因是多了几分含蓄。正如我形容我的博客(在书中),<一个href=\"http://blog.stephencleary.com/2012/07/dont-block-on-async-$c$c.html\"><$c$c>Result$c$c>/<$c$c>Wait$c$c>可能导致死锁和甚至会引起更微妙的僵局在异步
方法使用时。所以,当我阅读到code和我看到了一个结果
或等待
,这是一个直接的警告旗。如果你的的结果
/ 等待
是唯一正确的绝对肯定的那个任务已经完成。这不仅是很难一眼看出(在现实世界code),但它也更脆至code的变化。
The second reason is a little more subtle. As I describe on my blog (and in the book), Result
/Wait
can cause deadlocks, and can cause even more subtle deadlocks when used in an async
method. So, when I'm reading through code and I see a Result
or Wait
, that's an immediate warning flag. The Result
/Wait
is only correct if you're absolutely sure that the task is already completed. Not only is this hard to see at a glance (in real-world code), but it's also more brittle to code changes.
这并不是说,结果
/ 等待
应的从不的使用。我遵循这些原则在我自己的code:
That's not to say that Result
/Wait
should never be used. I follow these guidelines in my own code:
- 异步code只能使用
的await
。 - 异步工具code(在库)可以偶尔使用
结果
/等待
如果code真的会需要它。这种用法大概应该有意见。 - 的并行的任务code可以使用
结果
和等待
。
在应用程序
- Asynchronous code in an application can only use
await
. - Asynchronous utility code (in a library) can occasionally use
Result
/Wait
if the code really calls for it. Such usage should probably have comments. - Parallel task code can use
Result
andWait
.
请注意:(1)是目前常见的情况,因此我倾向于使用等待
无处不在,对待其他案件作为例外的一般规则。
Note that (1) is by far the common case, hence my tendency to use await
everywhere and treat the other cases as exceptions to the general rule.
这篇关于等待上一个完成的任务一样task.Result?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!