JavaScript Web Worker - close() 与 terminate()

JavaScript Web Worker - close() vs terminate()

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

我什么时候会用一个代替另一个?

close() 方法在 worker 的范围内可见。 terminate()方法是worker对象接口的一部分,可以调用"from the outside".

如果您在主脚本中创建了一个 worker 并想从该脚本中停止它,您应该在 worker 对象上调用 terminate()。如果你想从 worker 代码中停止 worker(例如作为对外部消息的响应),你应该调用 close() 方法。

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

确实,close() 函数在 Worker 的范围内是可见的。

terminate() 从外部可见(即:调用 worker 的脚本可以使用此函数将其关闭)

TBH 一开始这有点令人困惑,但是一旦你实施了你就会习惯它

我发现 self.close() 过度终止的一个很​​好的用例。在我的 web worker 中,我有一个 setInterval 函数,它正在接收和回发一个对象位置。使用 terminate 会永远杀死 web worker,所以我无法将播放消息发送回 worker。同时关闭它,允许我重新打开它并重新启动计时器。

在 React 中使用 web worker 时的其他差异:

  1. 如果你用terminate,你直接调用api,就是synchronous
  2. 如果你使用close,你需要调用postMessage并发送一个signal/message,这样worker就可以在它的范围内杀死自己。据我所知,postMessageNOT 同步的。

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.

嗯,简单点。

// immediately terminate the main JS file
worker.terminate();
// stop the worker from the worker code.
self.close();