dart-archive / isolate

Makes working with Dart isolates easier.
https://pub.dev/packages/isolate
BSD 3-Clause "New" or "Revised" License
90 stars 34 forks source link

"Something" keeps running when isolate TimeOut #38

Closed shinayser closed 3 years ago

shinayser commented 4 years ago

Check this simple code:

void main(List<String> arguments) {
  IsolateRunner.spawn().then((isolate) {
    isolate.run(
      _calculate,
      null,
      timeout: Duration(milliseconds: 3000),
      onTimeout: () {
        print('Time out!');
        isolate.close();
        return true;
      },
    ).then((_) {
      isolate.close();
      return "Worked!";
    }).then(print);
  });
}

Future<bool> _calculate(_) async {
  await Future.delayed(Duration(milliseconds: 2000));
  return true;
}

This code works fine and it outputs:

Worked!

Process finished with exit code 0

Cool! But if you change the timeout duration from 3000 to 1000, it outputs:

Time out!
Worked!

...and the program keeps running. It never prints Process finished with exit code 0. Probably there is something leaking when the timeout methods get called.

lrhn commented 3 years ago

This is due to the second call to close never completing. The result of onTimeout (true) is passed to the following then, and then you call close again. Calling close sends a "terminate" request to the runner, and waits for a response. Since the runner was killed by the first call to close, that response never comes and the port waiting for it is keeping the isolate alive.

I'll make later calls to close use the result of the first call.