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.
Await:
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();
Is one preferred over the other in particular situations?
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.
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
.
I suggest you try implementing a slightly larger sequence of operations with both await
and Task.ContinueWith
- it can be a real eye-opener.
See more on this question at Stackoverflow