顺序等待VS继续等待 [英] Sequential await VS Continuation await

查看:124
本文介绍了顺序等待VS继续等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道由两个(或多个)异步和从属(第一个必须完成才能执行第二个)操作组成的异步代码的最佳/正确方式是什么.

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();

具有延续性的示例:

await RunFirstOperationAsync()
    .ContinueWith(t => RunSecondOperationAsync());

推荐答案

如果可能的话,您想使用await.

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

ContinueWith有很多问题.我在为什么ContinueWith是危险",该内容建立在我先前在为什么StartNew很危险(它们有很多相同的问题).

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).

尤其是:

  • ContinueWith没有很好的默认TaskScheduler.默认任务计划程序是TaskScheduler.Current(不是TaskScheduler.Default),并且如果需要,必须手动完成在当前SynchronizationContext上的恢复.
  • ContinueWith具有非理想的默认选项.对于异步代码,至少需要DenyChildAttachExecuteSynchronously.
  • ContinueWith无法理解异步延续,通常需要额外的Unwrap调用来解决此限制.
  • ContinueWith以令人惊讶的方式对待其CancellationToken自变量.此博客中有关的更多信息我的帖子.
  • 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.

这篇关于顺序等待VS继续等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆