Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stopping the pool on Exception #61

Open
xErik opened this issue Jan 29, 2023 · 0 comments
Open

Stopping the pool on Exception #61

xErik opened this issue Jan 29, 2023 · 0 comments

Comments

@xErik
Copy link

xErik commented Jan 29, 2023

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant