Skip to content

Add possibility to truly cancel/dispose Fututre #42855

@anowakiteo

Description

@anowakiteo

Hi,
In current version of dart there is possibility to cancel Future, using CancelableOperation. But this solutions do only one thing, cancels listening for result.

There is missing possibility to truly cancel working Future.

Eg. This small piece of code will run, even all futures are canceled:

 for (int j = 0; j < 10; j++) {
    Future<void> longOne = () async {
      await Future.delayed(Duration(seconds: 1));
      int i = 0;
      int b = 0;
      Random c = Random(j);
      while (++i < 42949672) {
        b = c.nextInt(i);
      }
      print("Debug: index: $j");
      return;
    }().timeout(Duration(milliseconds: 100)).catchError((e) {
      print(e);
    });
    CancelableOperation cancelableOperation = CancelableOperation.fromFuture(longOne, onCancel: () {
      print("cancel called");
    });
    cancelableOperation.cancel();
  }

output:

cancel called
cancel called
cancel called
cancel called
cancel called
cancel called
cancel called
cancel called
cancel called
cancel called
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
TimeoutException after 0:00:00.100000: Future not completed
Debug: index: 0
Debug: index: 1
Debug: index: 2
Debug: index: 3
Debug: index: 4
Debug: index: 5
Debug: index: 6
Debug: index: 7
Debug: index: 8
Debug: index: 9

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-core-librarySDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.library-asynctype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions