await 和 ContinueWith 之间的区别 [英] Difference between await and ContinueWith

查看:16
本文介绍了await 和 ContinueWith 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下以下示例中 awaitContinueWith 是否是同义词.我是第一次尝试使用 TPL,并且已经阅读了所有文档,但不明白其中的区别.

Can someone explain if await and ContinueWith are synonymous or not in the following example. I'm trying to use TPL for the first time and have been reading all the documentation, but don't understand the difference.

等待:

String webText = await getWebPage(uri);
await parseData(webText);

继续:

Task<String> webText = new Task<String>(() => getWebPage(uri));
Task continue = webText.ContinueWith((task) =>  parseData(task.Result));
webText.Start();
continue.Wait();

在特定情况下,一个比另一个更受欢迎吗?

Is one preferred over the other in particular situations?

推荐答案

在第二个代码中,您同步等待继续完成.在第一个版本中,该方法会在遇到第一个尚未完成的 await 表达式时立即返回给调用者.

In the second code, you're synchronously waiting for the continuation to complete. In the first version, the method will return to the caller as soon as it hits the first await expression which isn't already completed.

它们非常相似,因为它们都安排了延续,但是一旦控制流变得稍微复杂一点,await 就会导致 简单得多的代码.此外,正如 Servy 在评论中所指出的,等待任务将解开"聚合异常,这通常会导致更简单的错误处理.同样使用 await 将在调用上下文中隐式安排继续(除非您使用 ConfigureAwait).没有什么是不能手动"完成的,但是使用 await 做起来要容易得多.

They're very similar in that they both schedule a continuation, but as soon as the control flow gets even slightly complex, await leads to much simpler code. Additionally, as noted by Servy in comments, awaiting a task will "unwrap" aggregate exceptions which usually leads to simpler error handling. Also using await will implicitly schedule the continuation in the calling context (unless you use ConfigureAwait). It's nothing that can't be done "manually", but it's a lot easier doing it with await.

我建议你尝试使用 awaitTask.ContinueWith 来实现一个稍微大一点的操作序列 - 这会让你大开眼界.

I suggest you try implementing a slightly larger sequence of operations with both await and Task.ContinueWith - it can be a real eye-opener.

这篇关于await 和 ContinueWith 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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