You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查Dart中的Isolate是否已被终止?

Dart Isolate 终止状态检测问题

Dart 的 Isolate 类确实没有提供直接的属性来判断该隔离是否已经终止。

要检测 Isolate 的终止状态,你可以用以下两种常用方案:

  • 添加退出监听器:使用 Isolate.addOnExitListener 方法,给目标 Isolate 注册一个回调端口,当 Isolate 终止时会向这个端口发送消息。示例代码:
    final receivePort = ReceivePort();
    isolate.addOnExitListener(receivePort.sendPort);
    receivePort.listen((_) {
      print('Isolate 已终止');
      receivePort.close();
    });
    
  • 自定义状态跟踪:在 Isolate 的入口函数末尾发送一个"终止完成"的消息到主隔离的端口,主隔离通过监听这个消息来标记 Isolate 的状态。示例代码:
    // 主隔离
    final receivePort = ReceivePort();
    final isolate = await Isolate.spawn(isolateEntry, receivePort.sendPort);
    
    bool isIsolateAlive = true;
    receivePort.listen((message) {
      if (message == 'exit') {
        isIsolateAlive = false;
        receivePort.close();
      }
    });
    
    // Isolate 入口函数
    void isolateEntry(SendPort sendPort) {
      // 执行任务
      // ...
      // 任务结束发送终止消息
      sendPort.send('exit');
    }
    

内容的提问来源于stack exchange,提问作者Hammerhead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:10:29