await for(receivePort中的var msg)和receivePort.listen()之间有什么区别?

时间:2019-07-12 09:51:17

标签: dart dart-isolates

我正在学习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()?乍一看,它是一样的。还是不?

1 个答案:

答案 0 :(得分:1)

我可以说是不一样的。 listenawait 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");
}