【问题标题】:How can I await Task.WhenAll( ... ).ContinueWith( AnotherAwaitable )?我如何等待 Task.WhenAll( ... ).ContinueWith( AnotherAwaitable )?
【发布时间】:2015-07-23 19:15:35
【问题描述】:

我有以下代码 -

await Task.WhenAll(TaskList /*List of Task objects*/);
await AnotherAwaitableMethod( );

这很好用并且是必要的,因为AnotherAwaitableMethod 依赖于确保TaskList 中的任务在执行之前完成。

不过,我想说一些类似的话

await Task.WhenAll(TaskList).ContinueWith( /*AnotherAwaitableMethod call?*/ );

这可能吗?我是不是误解了Task.ContinueWith的目的?

【问题讨论】:

  • 你可以这样做:await Task.WhenAll(TaskList).ContinueWith(_ => AnotherAwaitableMethod( )).Unwrap();。但是,如果第一个代码已经有效,为什么还需要它呢?
  • 好吧,问题中的关键词是,不是需要,而是语义 - 这是一种编码偏好;我希望电话在一行中。
  • @Will 你可以通过await AnotherAwaitableMethod(await Task.WhenAll(TaskList));把它放在同一行。
  • 为什么不Task.WhenAll(Task.WhenAll(TaskList), AnotherAwaitableMethod())

标签: c# async-await task


【解决方案1】:
  await Task.WhenAll(TaskList /*List of Task objects*/);
  await AnotherAwaitableMethod( );

 await Task.WhenAll(TaskList /*List of Task objects*/).ContinueWith(_ => {AnotherAwaitableMethod();}).Unwrap();

的行为几乎相同。然而,如果你使用它的overloads,使用 ContinueWith 会给你很大的移动能力。 使用 ContinueWith 的主要原因之一是当您想根据第一个任务的结果有条件地执行 AnotherAwaitableMethod 或当您想使用 TaskContinuationOptions 控制上下文时

【讨论】:

  • 这就是我想知道的;谢谢。
  • 你可以用 await 很容易地“根据第一个的结果有条件地”执行第二个任务,而用 ContinueWith 实际上更难做到。此外,传递回调只会扭曲您的调用堆栈,以防出现异常并使调试更加困难。使用这样的回调首先会破坏 async/await 的意义。
  • 这将返回Task<Task>,因为AnotherAwaitableMethod 返回Task。您需要使用Unwrap()。还有TaskFactory.ContinueWhenAll。但 Asad 是对的,你不应该偏爱任何形式的 ContinueWith 而不是 await、@Will。
猜你喜欢
  • 2022-11-15
  • 2023-03-26
  • 1970-01-01
  • 2016-08-22
  • 2018-05-11
  • 2014-02-21
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
相关资源
最近更新 更多