从隔离功能调用异步功能

Ani*_*753 5 dart dart-isolates flutter

我正在尝试从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');
  }
}
Run Code Online (Sandbox Code Playgroud)

以上类的用法:

final IsolateExample _isolate = new IsolateExample();
Run Code Online (Sandbox Code Playgroud)

上面的代码看起来很简单,但从未调用过asyncFunction。我不知道这为什么失败。

Oma*_*att 0

Isolate 只会运行一次计算。如果您想按时间间隔调用隔离内部的函数,您可以使用Timer.periodic() ,类似于本文中的演示方式

一旦你完成了隔离中的函数的运行,你可以用isolate.kill()- 来终止它,因为isolate包含Isolate.spawn()