Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential await VS Continuation await

I was wondering what is the best/correct way of writing asynchronous code that is composed of two (or more) async and dependent (the first have to finish to execute second) operations.

Example with async/await:

await RunFirstOperationAsync();
await RunSecondOperationAsync();

Example with Continuation:

await RunFirstOperationAsync()
    .ContinueWith(t => RunSecondOperationAsync());
like image 933
Aleksander Bethke Avatar asked Apr 22 '16 15:04

Aleksander Bethke


People also ask

Is async await synchronous?

Or we can say await is only used with an async function. The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .

What is the difference between task run and async await?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

What is difference between async and await in C#?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.

What is a continuation task?

In the Task Parallel Library, the same functionality is provided by continuation tasks. A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.


1 Answers

You'd want to use await if you possibly can.

ContinueWith has a number of issues. I describe this briefly in my blog post on why ContinueWith is dangerous, which builds on my earlier blog post on why StartNew is dangerous (they share many of the same issues).

In particular:

  • ContinueWith does not have a good default TaskScheduler. The default task scheduler is TaskScheduler.Current (not TaskScheduler.Default), and resuming on the current SynchronizationContext must be done by hand if desired.
  • ContinueWith has non-ideal default options. For asynchronous code, you would want DenyChildAttach and ExecuteSynchronously, at least.
  • ContinueWith does not understand asynchronous continuations, which generally requires an additional Unwrap call to work around this limitation.
  • ContinueWith treats its CancellationToken argument in a surprising way. More on that in this blog post of mine.

These arguments are all summarized on my blog post on Task continuations. await does not have any of these drawbacks.

like image 142
Stephen Cleary Avatar answered Sep 18 '22 15:09

Stephen Cleary