简体   繁体   中英

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.

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. Eg, 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.

I don't think so.

Async/await was not made to replace TPL all together, but to supplement it by making simple operations cleaner.
If you still need extra configuration, you'll have to stick to tasks, or you could try implementing a custom awaiter with this behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM