闭包能发送到 SendPort 吗?

huangapple go评论62阅读模式
英文:

Can a closure be sent to a SendPort

问题

我正在实现双独立体应用程序。在此范围内,我正在探索通过 SendPort 发送闭包的可能性。文档 表示,在隔离体共享相同代码的情况下,可以发送任何东西,但有一些例外情况。但当我尝试调用此代码时

port.send(() {});

我收到一个错误:
> E/flutter (26634): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常: 参数无效:隔离消息中的非法参数: (对象是闭包 - 函数'<匿名闭包>':.)

这是预期行为,只是不能通过 SendPort 发送函数吗?

我的环境是:

Flutter 3.3.9 • 稳定通道 • https://github.com/flutter/flutter.git
框架 • 修订版 b8f7f1f986(6 个月前) • 2022-11-23 06:43:51 +0900
引擎 • 修订版 8f2221fbef
工具 • Dart 2.18.5 • DevTools 2.15.0
英文:

I'm working on implementation two-isolates app. In this scope I'm exploring a possibility to send a closure via SendPort. The documentation says that in case isolates share same code anything can be sent with some exceptions. But when I try to call this

port.send(() {});

I get an error:
> E/flutter (26634): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function '<anonymous closure>':.)

Is that expected behavior and one just can't send functions via SendPort?

My environment is:

Flutter 3.3.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision b8f7f1f986 (6 months ago) • 2022-11-23 06:43:51 +0900
Engine • revision 8f2221fbef
Tools • Dart 2.18.5 • DevTools 2.15.0

答案1

得分: 1

自Dart 2.15版本开始,默认启用隔离组,使用Isolate.spawn()启动的隔离现在共享相同的代码,并允许在隔离消息中包含闭包。

如果闭包的封闭上下文包含不可发送的消息,则可能会失败。
由于此问题,通常不建议将闭包发送给隔离。请参阅dart-lang/sdk#36983,其中与另一个问题相关的讨论。

有关更多信息,请查看Dart 2.15.0变更日志中的Dart VM部分

英文:

Since Dart 2.15, which enables isolate groups by default, isolates started with Isolate.spawn() share the same code and allow including closures in inter-isolate messages.

This may fail if the closure's enclosing context contains messages that are not sendable.
Sending closures to isolates is generally discouraged due to this issue. See dart-lang/sdk#36983, where this is discussed in relation to another issue.

See the Dart VM section of the Dart 2.15.0 changelog for more information.

huangapple
  • 本文由 发表于 2023年5月10日 15:06:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定