【问题标题】:Dart : what happens when two or more tasks are waiting on the same FutureDart:当两个或多个任务等待同一个 Future 时会发生什么
【发布时间】:2022-11-26 21:42:26
【问题描述】:

在 Dart 中,当两个或多个任务在同一个 Future 上等待时,当 Future 完成时,任务是否按照它们执行 await 的顺序得到通知/运行,即第一个执行 await 的是第一个运行的。

此代码是否保证输出 2

int res = 0;

Future<void> foo1 () async
{
  await Future.delayed(Duration(seconds: 2));
  res = 2;
}


void main() async
{
  await foo1();
  print(res);
}

【问题讨论】:

  • 是的,foo1函数执行完后,main方法中的print语句会继续。
  • 有两个等待正在等待同一个未来。你怎么知道哪个先“运行”?

标签: dart


【解决方案1】:

代码打印 2。

int res = 0;

Future<void> foo1() async {
  await Future.delayed(const Duration(seconds: 2));
  res = 2;
  print('foo1 res: $res');
}

void main() async {
  await foo1();
  print('last res: $res');
}

输出

?‍? 飞镖 await.dart

foo1 res: 2
last res: 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2017-08-03
    • 2018-08-17
    相关资源
    最近更新 更多