Dart Isolates' pause function not working as expected

南楼画角 提交于 2020-06-25 04:25:05

问题


I've been playing around with Dart Isolates and have run into a problem using the isolate.pause(); function.

import 'dart:io';
import 'dart:isolate';

main(){
  ReceivePort receivePort = new ReceivePort();
  Isolate.spawn(isolateEntryPoint, receivePort.sendPort).then((isolate){
    isolate.pause(isolate.pauseCapability);
  });
}

void isolateEntryPoint(SendPort sendPort){
  while(true){
    print("isolate is running");
    sleep(new Duration(seconds: 2));
  }
}

In my example the isolate basically just prints something out every 2 seconds.

From what I read on the docs, my understanding is that the above code should:

  1. Spawn an isolate
  2. Promptly pause that isolate

But it's not working, the isolate is still running and printing "isolate is running" every 2 seconds even after I tell it to pause.

I'm aware that you can start an isolate in a paused state by passing in the paused: true optional parameter: Isolate.spawn(isolateEntryPoint, receivePort, paused: true).... Ultimately however I would like to be able to pause the isolate at any point, not just right off the bat.

The only documentation I could find about using this was on the official dart docs, so it's possible I'm using the isolate.pause() function incorrectly. But either way a code example demonstrating the correct usage of this function would be greatly appreciated.


回答1:


You are correct that this is not working as you expected.

The isolate pause functionality works by pausing the event queue. The currently executing event will complete, and then no further events are processed until you resume the isolate. The pause does not affect running code.

In this code, the isolate entry point is running an infinite loop with a built-in delay. It never returns to the event queue. If you scheduled any asynchronous operations in the loop, they would never execute. The sleep primitive sleeps the entire isolate, but it's no different from doing nothing at all (it just takes longer).

You try to "promptly pause" the new isolate, but isolates run concurrently, and the new isolate has already started executing its entry point function when the Isolate object is returned.

It might be possible to change the isolate functionality in the future, to be more eager in handling control messages, if we don't have to support isolates compiled to JavaScript any more, but currently isolates control messages are effectively asynchronous, they only take effect between the events of the Dart event queue.



来源:https://stackoverflow.com/questions/48130287/dart-isolates-pause-function-not-working-as-expected

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