【问题标题】:Call async function from Isolate function从隔离函数调用异步函数
【发布时间】:2022-04-27 10:31:09
【问题描述】:

我正在尝试从 Isolate 函数调用异步函数。

class IsolateExample {

  final ReceivePort port = new ReceivePort();

  IsolateExample(){
     Isolate.spawn(isolateFunction, port.sendPort);
  }

  static isolateFunction(SendPort port){
    print('inside isolateFunction');
    asyncFunction();
  }

  static void asyncFunction() async {
    print('inside asyncFunction');
  }
}

上述类的用法:

final IsolateExample _isolate = new IsolateExample();

上面的代码看起来很简单,但 asyncFunction 永远不会被调用。我不知道为什么会失败。

【问题讨论】:

  • 我已经简化了上面的内容。在实际代码中,我需要随着时间的推移返回多个值。我猜 compute() 不支持多次返回。
  • 否,compute 仅支持单个同步返回值。支持单个异步返回值存在一个未解决的问题。
  • 嗯,到目前为止,该样本没有问题。我可以看到print('inside asyncFunction')

标签: flutter dart dart-isolates


【解决方案1】:

Isolate 只会运行一次您的计算。如果您想间隔调用隔离内的函数,您可以使用Timer.periodic(),类似于在此post 上演示的方式。

在隔离区中运行完函数后,您可以使用 isolate.kill() 终止它 - 假设 isolate 包含 Isolate.spawn()

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多