gpt4 book ai didi

dart - 无法暂停 Dart 隔离

转载 作者:行者123 更新时间:2023-12-03 02:44:24 32 4
gpt4 key购买 nike

我希望在 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 仍会继续运行。我找到了 this answer它说这是因为他们的情况是无限循环,但我没有使用任何循环。那么我在这里做错了什么?

最佳答案

您的问题是您在 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实现更像是“立即停止所有执行 N 次”,这更符合您的期望:

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

关于dart - 无法暂停 Dart 隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62122534/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com