问题描述
我正在尝试使用isolate.addOnExitListener(...)来跟踪隔离当前是否正在运行(以及将来是否出错)。但是,以下代码片段无法正常运行:
I'm trying to track whether the isolate is currently running or not (and in the future whether it has errored out) using isolate.addOnExitListener(...). However, the following snippet of code is not working how I would expect:
items.forEach((name, item) async {
Isolate isolate = await Isolate.spawnUri(...);
item.status = "running";
ReceivePort receivePort = new ReceivePort();
isolate.addOnExitListener(receivePort.sendPort);
receivePort.listen((message){
if (message == null) {
print("Item exited: ${item.name}");
item.status = "stopped";
}
});
});
items映射包含3个值,每个值都有不同的名称:item1,item2,item3
The "items" map contains 3 values, each with a distinct name: item1, item2, item3
运行此代码时,我得到的唯一输出是:
项目退出:item3
When I run this code, the only output I get is:"Item exited: item3"
我期望以下输出(由于隔离是异步的,因此不一定按顺序输出):
项目退出:item1
项目退出:item2
项目退出:item3
I expected the following output (not necessarily in order since isolates are asynchronous):"Item exited: item1""Item exited: item2""Item exited: item3"
以下是在隔离中运行的代码:
Here is the code being run in the isolates:
import 'dart:io';
main(List args) {
print('Hello world: standard out!');
stderr.writeln('Hello world: standard error!');
}
似乎关闭已丢失。我在这里做错什么了吗?有没有更好的方法来跟踪隔离区的状态?
It seems like the closure is being lost. Am I doing something wrong here? Is there a better way to track the state of an isolate?
预先感谢!
推荐答案
如果要绝对确保可以在隔离的任何代码执行之前在隔离中安装onExit和onError侦听器,则可以生成已暂停的隔离。请参阅有关的文档。
If you want to make absolutely sure that you can install onExit and onError listeners in an isolate before any of the isolate's code executes, then you can spawn the isolate paused. See documentation about spawnUri.
这里是一个示例:
var isolate = await Isolate.spawnUri(myUri, args, message, paused: true);
var receivePort = new ReceivePort();
isolate.addOnExitListener(receivePort.sendPort);
receivePort.listen((message){
if (message == null) { // A null message means the isolate exited
print("Item exited: ${item.name}");
item.status = "stopped";
}
});
isolate.resume(isolate.pauseCapability);
注册了适当的侦听器后,可以使用。
Once you have registered the appropriate listeners, you can start the newly created isolate with resume.
这与初次握手的建议非常相似,但是在这种情况下,它内置在库中。
This is very similar to the suggestion of an initial handshake, but in this case it is builtin to the library.
希望这会有所帮助
-伊万
这篇关于在Dart中跟踪隔离状态的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!