JavaScript Web Worker - close()vs terminate()

Joh*_*Lee 18 web-worker

我并不完全理解Web Workers的close()和terminate()方法之间的区别.我已经阅读了这里的描述,它似乎在做同样的事情? http://www.w3.org/TR/workers/

我何时会使用一个而不是另一个?

Paw*_*żyk 48

close()方法在工作者范围内可见.该terminate()方法是工作对象接口的一部分,可以"从外部"调用.

如果在主脚本中创建一个worker并希望从该脚本中停止它,则应该调用terminate()worker对象.如果要从工作程序代码中停止工作程序(例如,作为对外部消息的响应),则应调用该close()方法.

资料来源:https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Terminating_a_worker

  • 是否可以检查工作人员是否仍然活着/正在运行? (2认同)

Yum*_*Gui 5

在 React 中使用 Web Worker 时的其他差异:

  1. 如果你使用terminate,你只需调用 api ,它是synchronous
  2. 如果您使用close,您需要调用postMessage并发送信号/消息,以便工作人员可以在其范围内杀死自己。据我所知,postMessage是同步的。NOT

问题是close,如果你想在unmount组件时杀死worker,你需要这样做synchronously,否则,你may会收到警告,特别是当你尝试清理ComponentWillUnmount生命周期钩子或useEffect钩子中的东西时(否则,将会有多个僵尸网络工作者实例还活着)。

该警告看起来像:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

或者:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.