void func(String dummy) {
String? name = stdin.readLineSync();
print(name);
}
void main(List<String> args) {
Isolate.spawn(func, "Testing");
}
为什么我的程序不提示用户输入..并等待我输入。相反,它只是退出。有人可以帮我解释一下吗?不知道该去哪里寻找。
我确实发现了一个类似的问题,他们在其中使用 while 循环并使用 readLineSync
..并且由于 dart 的单线程 ..它在那里不起作用。
最佳答案
当 main-isolate 不再需要执行任何操作、事件队列上没有事件并且不订阅任何事件源(这会导致新事件添加到事件队列中)时,Dart 程序将终止(如 接收端口
或计时器
)。生成的隔离株是否仍在执行并不重要,因为它们只会被杀死。
您需要让 main-isolate 执行某些操作,或者使 main-isolate 使用 ReceivePort
/SendPort
订阅来自生成的隔离的信号,因为这将防止 main-isolate 被终止(因为它订阅了一个可能会在事件队列上添加新事件的事件源)。
在 Isolate
对象上使用 addOnExitListener
的示例可以在此处查看:
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
void func(String dummy) {
print('Enter your name:');
final name = stdin.readLineSync();
print('Your name is: $name');
}
Future<void> main(List<String> args) async {
final onExitReceivePort = ReceivePort();
final isolate = await Isolate.spawn(func, "Testing");
isolate.addOnExitListener(
onExitReceivePort.sendPort,
response: 'ReadLineIsolateStopped',
);
// Listen on spawned isolate is stopped event
await for (final onExitEvent in onExitReceivePort) {
print('Got event: $onExitEvent');
onExitReceivePort.close();
}
}
一旦我们收到一个事件(因为生成的隔离消失了),我们就会关闭onExitReceivePort
,这将停止我们的主隔离和程序的其余部分。
关于dart - 为什么 readLineSync 在 Isolate 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70189318/