Sequential processing of a variable number of async functions in Dart

蹲街弑〆低调 提交于 2020-01-11 11:35:50

问题


I need to repeatedly call an asynchronous function in Dart, let's call it expensiveFunction, for a variable number of arguments. However, since each call is quite memory consuming, I cannot afford to run them in parallel. How do I force them to run in sequence?

I have tried this:

argList.forEach( await (int arg) async {
  Completer c = new Completer();
  expensiveFunction(arg).then( (result) {
    // do something with the result
    c.complete();
  });
  return c.future;
});

but it hasn't had the intended effect. The expensiveFunction is still being called in parallel for each arg in argList. What I actually need is to wait in the forEach loop until the expensiveFunction completes and only then to proceed with the next element in the argList. How can I achieve that?


回答1:


You'll want to use a classic for loop here:

doThings() async {
  for (var arg in argList) {
    await expensiveFunction(arg).then((result) => ...);
  }
}

There are some nice examples on the language tour.




回答2:


You can achieve required result using semaphore.
The maxCount variable controls the number of asynchronous operations that can be performed simultaneously.

Example:

import 'package:semaphore/semaphore.dart';

Future<void> main() async {
  final maxCount = 1;
  final s = LocalSemaphore(maxCount);
  argList.forEach((arg) async {
    try {
      await s.acquire();
      await expensiveFunction(arg);
    } finally {
      s.release();
    }
  });
}

Future<void> expensiveFunction(String arg) async {
  report('Start $arg');
  await Future.delayed(Duration(seconds: 1));
  report('Stop  $arg');
}

void report(String text) {
  print('${DateTime.now()}: $text');
}

final argList = ['a', 'b', 'c'];

Result:

2019-12-30 20:22:06.586853: Start a
2019-12-30 20:22:07.596096: Stop  a
2019-12-30 20:22:07.597096: Start b
2019-12-30 20:22:08.606753: Stop  b
2019-12-30 20:22:08.606753: Start c
2019-12-30 20:22:09.616570: Stop  c

To see the difference, change the value of maxCount:

final maxCount = 2;
2019-12-30 20:24:12.170537: Start a
2019-12-30 20:24:12.176538: Start b
2019-12-30 20:24:13.179384: Stop  a
2019-12-30 20:24:13.180384: Start c
2019-12-30 20:24:13.180384: Stop  b
2019-12-30 20:24:14.187032: Stop  c
Exited



来源:https://stackoverflow.com/questions/45874546/sequential-processing-of-a-variable-number-of-async-functions-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!