pool icon indicating copy to clipboard operation
pool copied to clipboard

Stopping the pool on Exception

Open xErik opened this issue 3 years ago • 0 comments

What is the proper way to handle an Exceception from a queued function:

How to clear all queued functions and to stop the pool?

The following code catches the Exception. But there is no option to clear the still queued functions or to exit the pool in general.

import 'package:pool/pool.dart';

main() async {
  final pool = Pool(2, timeout: Duration(seconds: 30));

  final List<Future> futures = [];

  try {
    for (var i = 0; i < 10; i++) {
      futures.add(
        pool.withResource(
          () => Future.delayed(
            Duration(seconds: 1),
            () {
              if (i == 5) {
                throw 'Oh no!';
              }
              print(i);
              return i;
            },
          ),
        ),
      );
    }

    await Future.wait(futures, eagerError: true);
  } catch (e) {
    print('CAUGHT: $e');
  }
}

Output

0
1
2
3
4
CAUGHT: Oh no!
6
7
8
9

Workaround

This workaround uses a global stopSignal that shortcuts the still queued functions.

import 'package:pool/pool.dart';

main() async {
  bool stopSignal = false;

  final pool = Pool(2, timeout: Duration(seconds: 30));

  final List<Future> futures = [];

  try {
    for (var i = 0; i < 10; i++) {
      futures.add(
        pool.withResource(
          () => stopSignal == true
              ? Future(() => null)
              : Future.delayed(
                  Duration(seconds: 1),
                  () {
                    if (i == 5) {
                      throw 'Oh no!';
                    }
                    print(i);
                    return i;
                  },
                ),
        ),
      );
    }

    await Future.wait(futures, eagerError: true);

  } catch (e) {
    print('CAUGHT: $e');
    stopSignal = true;
  }
}
0
1
2
3
4
CAUGHT: Oh no!
6

xErik avatar Jan 29 '23 16:01 xErik