我正在学习Dart:
main() async
{
ReceivePort receivePort = ReceivePort();
Isolate.spawn(echo, receivePort.sendPort);
// await for(var msg in receivePort)
// {
// print(msg);
// }
receivePort.listen((msg) { print(msg);} );
}
echo(SendPort sendPort) async
{
ReceivePort receivePort = ReceivePort();
sendPort.send("message");
}
我不知道何时使用await for(var msg in receivePort)
更好,何时使用receivePort.listen()
?乍一看,它是一样的。还是不?
答案 0 :(得分:1)
我可以说是不一样的。 listen
和await for
有所不同。 listen
仅注册处理程序,然后继续执行。 await for
保持执行直到流关闭。
如果您要在侦听/等待行之后添加行print('Hello World')
,
使用监听时,您将看到Hello world。
Hello World
message
因为在此之后继续执行。但是等待着,
在关闭流之前不会有任何问候。
import 'dart:isolate';
main() async
{
ReceivePort receivePort = ReceivePort();
Isolate.spawn(echo, receivePort.sendPort);
// await for(var msg in receivePort)
// {
// print(msg);
// }
receivePort.listen((msg) { print(msg);} );
print('Hello World');
}
echo(SendPort sendPort) async
{
ReceivePort receivePort = ReceivePort();
sendPort.send("message");
}