【问题标题】:Is there a better way to chain async tasks other than using ContinueWith method? [duplicate]除了使用 ContinueWith 方法之外,还有更好的方法来链接异步任务吗? [复制]
【发布时间】:2020-08-29 19:22:30
【问题描述】:

我正在像这样链接我的异步任务,

await MyTask_1().ContinueWith(async x=>
{
    // do other stuff
    await MyTask_2().ContinueWith(async y => 
    {
        await MyTask_3().ContinueWith(async z => 
        {
            // and more tasks
        });
    }); 
});

我想在前一个任务完成后运行一个任务,所以我只找到了链接它们的方法。

但是还有其他不那么难看、更简洁或更短的方法来实现这一点吗?

【问题讨论】:

  • 您可能在这里遗漏了明显的内容,只需一个接一个地写。 await MyTask_1(); await MyTask_2(); await MyTask_3(); await 操作符可以发挥所有作用。

标签: c# async-await


【解决方案1】:

await 已经暂停当前代码流(并释放线程)并等待异步任务,因此在此之前它不会执行下一行代码。你应该能够简单地写

await MyTask_1();
await MyTask_2();
await MyTask_3();

这就是为什么它被称为await

【讨论】:

  • 太棒了!谢谢!所以,如果我写这样的东西await MyTask_1(); int i =1; NonAsyncMethod(); await MyTask_2(); 它仍然会等待第一个任务完成然后会运行非同步方法,然后会调用 mytask 2 异步任务,对吗?
  • 是的。试试看,自己看看,测试起来很简单。
  • Nitpick:它不会“暂停线程”,而是释放线程去做其他事情。它暂停当前的代码路径。
猜你喜欢
  • 2011-08-28
  • 1970-01-01
  • 2021-08-15
  • 2015-12-08
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多