await for(receivePort中的var msg)和receivePort.listen()之间有什么区别? [英] What difference between await for(var msg in receivePort) and receivePort.listen()?

查看:66
本文介绍了await for(receivePort中的var msg)和receivePort.listen()之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习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(receivePort中的var msg),什么时候使用 receivePort.listen()?乍一看,它是一样的.还是不?

I can't understand when it's better to use await for(var msg in receivePort) and when receivePort.listen()? By the first look it's doing same. Or not?

推荐答案

我可以说这是不一样的. listen awaiting 有所不同. listen 仅注册处理程序,然后继续执行.并且 await for 保持执行直到流关闭.

I can say it is not the same. There is difference with listen and await for. listen just registers the handler and the execution continues. And the await for hold execution till stream is closed.

如果您要在侦听/等待行之后添加一行 print('Hello World'),使用监听时,您将看到Hello world.

If you would add a line print('Hello World') after listen/await for lines, You will see Hello world while using listen.

Hello World
message

因为在那之后继续执行.但是等待着,

because execution continues after that. But with await for,

在关闭流之前不会有任何问候.

There will be no hello world until stream closed.

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");
}

这篇关于await for(receivePort中的var msg)和receivePort.listen()之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆