【问题标题】:Asynchronous programming in Dart isnt WorkingDart 中的异步编程不起作用
【发布时间】:2022-01-07 00:23:47
【问题描述】:

我在 Dart 中有这样的代码:

Future<void> dataProcessAsync() async {
    await Future.delayed(Duration(seconds: 2));
    print("Process Completed!");
}

void main() {
    print("Process 1");
    print("Process 2");
    dataProcessAsync();
    print("Process 3");
    print("Process 4");
}

一切正常且异步。结果如预期 (流程 1 - 流程 2 - 流程 3 - 流程 4 - 流程已完成!)

但是当我这样写代码时:

Future<void> dataProcessAsync() async {
    for(int i = 1; i <= 10000000000; i++){}
    print("Process Completed!");
}

void main() {
    print("Process 1");
    print("Process 2");
    dataProcessAsync();
    print("Process 3");
    print("Process 4");
}

它不能异步工作。然后它等待了 dataProcessAsync() 很长时间 继续流程 3。(流程 1 - 流程 2 - 流程已完成!- 流程 3 - 流程 4)

谁能告诉我发生了什么以及如何解决这个问题?

【问题讨论】:

    标签: dart asynchronous async-await


    【解决方案1】:

    async 方法同步运行,直到第一个 await。如果该方法从未到达await,它将运行完成并返回一个同步填充的Future

    这是设计使然,并在 Dart 网页上进行了描述:

    async 函数同步运行,直到第一个 await 关键字。这意味着在async 函数体内,第一个await 关键字之前的所有同步代码都会立即执行。

    https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多