Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set TaskContinuationOptions using async/await?

Can I have all the options like OnlyOnRanToCompletion, OnlyOnCanceled, NotOnFaulted, etc. using async/await? I can't find examples on how to achieve the same results as using Tasks, for instance:

Task.Factory.StartNew(foo).ContinueWith(bar, TaskContinuationOptions.NotOnRanToCompletion);

I'm not sure if simple conditional or exception handling can manage all the continuation behaviors available in explicit Tasks.

like image 931
natenho Avatar asked Oct 22 '13 21:10

natenho


People also ask

Does async-await make code synchronous?

Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.

How use async-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.

Is .result same as await?

await asynchronously unwraps the result of your task, whereas just using Result would block until the task had completed. See this explanantion from Jon Skeet.

Does async-await improve performance C#?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.


1 Answers

Can I have all the options like OnlyOnRanToCompletion, OnlyOnCanceled, NotOnFaulted, etc. using async/await?

You don't need to.

Instead of copious syntax using bit flags and lambda continuations, await supports a very natural try/catch syntax:

try
{
  await foo();
}
catch
{
  bar();
  throw;
}

I'm not sure if simple conditional or exception handling can manage all the continuation behaviors available in explicit Tasks.

They naturally handle None, NotOnCanceled, NotOnFaulted, NotOnRanToCompletion, OnlyOnCanceled, OnlyOnFaulted, and OnlyOnRanToCompletion. Most of the other flags only make sense for parallel tasks, not asynchronous tasks. E.g., AttachedToParent, HideScheduler, and PreferFairness don't make sense in the async world; DenyChildAttach, LazyCancellation, and ExecuteSynchronously should always be specified in the async world; and LongRunning never should be.

like image 101
Stephen Cleary Avatar answered Sep 30 '22 03:09

Stephen Cleary