Home > OS >  Dart : what happens when two or more tasks are waiting on the same Future
Dart : what happens when two or more tasks are waiting on the same Future

Time:11-26

In Dart, when two or more tasks are waiting on the same Future, when the Future completes, do the tasks get notified/run in the order that they did the await i.e. the first to do an await is the first to run.

Is this code guaranteed to output 2

int res = 0;

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


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

and what about this code, slightly less obvious

int res = 0;

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


Future<void> foo2 (Future<void> f1) async
{
  await f1;
  res = 2;
}

Future<void> foo3 (Future<void> f1) async
{
  await f1;
  res = 3;
}


void main() async
{
  res = 0;
  
  Future<void> f1 = foo1();
  foo3(f1);
  foo2(f1);
  await f1;
  print(res);
}

CodePudding user response:

Code printed 2.

int res = 0;

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

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

  •  Tags:  
  • dart
  • Related