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

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

问题描述

有人能解释,如果等待 ContinueWith 在下面的例子中代名词与否。我试图使用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);

ContinueWith

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

是在特​​定情况下pferred在另一个$ P $?

Is one preferred over the other in particular situations?

推荐答案

在第二code,你的同步的等待延续完成。在第一个版本,该方法将尽快返回给调用者,因为它击中了第一个等待这不是已经完成的前pression。

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 导致的简单code。此外,如在Servy评论中指出,等待任务将解包总例外,通常会导致简单的错误处理。还使用伺机将隐式安排在调用上下文的延续(除非你使用 ConfigureAwait )。这是什么,能不能做到手动,但它是一个更容易与做伺机

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.

我建议你试试实施操作既等待 Task.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天全站免登陆