无法暂停 Dart 隔离

Cannot pause Dart isolate

我希望在 Dart 中创建一个 Isolate,我可以通过编程方式暂停和恢复。这是我使用的代码。

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

void main() async {
  print("Starting isolate");
  Isolate isolate;
  ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(run, receivePort.sendPort);
  print("pausing");
  Capability cap = isolate.pause(isolate.pauseCapability);
  sleep(Duration(seconds: 5));
  print("Resuming");
  isolate.resume(cap);
}

void run(SendPort sendPort) {
  sleep(Duration(seconds: 2));
  print("Woke up, 1");
  sleep(Duration(seconds: 2));
  print("Woke up, 2");
  sleep(Duration(seconds: 2));
  print("Woke up, 3");
  sleep(Duration(seconds: 2));
  print("Woke up, 4");
  sleep(Duration(seconds: 2));
  print("Woke up, 5");
}

我收到 O/P 赞

Starting isolate
pausing
Woke up, 1
Woke up, 2
Resuming
Woke up, 3
Woke up, 4
Woke up, 5

但是我想实现

Starting isolate
pausing
<--- 5 second delay --->
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5

但即使在调用 pause() 之后,Isolate 仍保持 运行。我发现 并且它说这是因为他们的情况是无限循环,但我没有使用任何循环。那么我在这里做错了什么?

你的问题是你错过了 pause 隔离文档中的一个细节:

When the isolate receives the pause command, it stops processing events from the event loop queue. It may still add new events to the queue in response to, e.g., timers or receive-port messages. When the isolate is resumed, it starts handling the already enqueued events.

所以pause不会停止方法的执行,而只是确保在执行当前运行方法之后,它将停止从事件队列中提供更多工作。

虽然 sleep 的实现更像 "stop all execution right now for N time",这更符合您的期望:

Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.

为了使您的示例正常工作,您需要将 sleep 调用替换为您正在等待的 Future 个实例,因为这会在事件队列中添加事件。

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

Future<void> main() async {
  print("Starting isolate");
  Isolate isolate;
  ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(run, receivePort.sendPort);
  print("pausing");
  Capability cap = isolate.pause(isolate.pauseCapability);
  sleep(const Duration(seconds: 5));
  print("Resuming");
  isolate.resume(cap);
}

Future<void> run(SendPort sendPort) async {
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 1");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 2");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 3");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 4");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 5");
}

输出:

Starting isolate
pausing
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5