【发布时间】:2021-11-10 01:37:24
【问题描述】:
我并不完全理解 Web Workers 的 close() 与 terminate() 方法之间的区别。我已经阅读了这里的描述,它似乎在做同样的事情?? http://www.w3.org/TR/workers/
我什么时候会使用一个而不是另一个?
【问题讨论】:
标签: javascript web-worker
我并不完全理解 Web Workers 的 close() 与 terminate() 方法之间的区别。我已经阅读了这里的描述,它似乎在做同样的事情?? http://www.w3.org/TR/workers/
我什么时候会使用一个而不是另一个?
【问题讨论】:
标签: javascript web-worker
close() 方法在 worker 的作用域内可见。
terminate() 方法是工作对象接口的一部分,可以“从外部”调用。
如果您在主脚本中创建了一个工作器并希望从该脚本中停止它,您应该在工作器对象上调用terminate()。如果您想从工作代码中停止工作人员(例如作为对外部消息的响应),您应该调用close() 方法。
【讨论】:
terminate()一个工人,我认为你不能再使用它了。
确实,close() 函数在 Worker 范围内是可见的。
terminate() 从外部可见(即:调用 worker 的脚本可以使用此函数将其关闭)
TBH 一开始这有点令人困惑,但是一旦你实现了你就会习惯它
【讨论】:
我发现 self.close() over terminate 的一个很好的用例。在我的网络工作者内部,我有一个 setInterval 函数,用于接收和回发对象位置。使用终止会永远杀死网络工作人员,因此我无法将播放消息发送回工作人员。同时关闭它,让我重新打开它并重新启动计时器。
【讨论】:
在 React 中使用 web worker 时的其他区别:
terminate,你只需调用api,它是synchronous
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.
【讨论】:
嗯,很简单。
// immediately terminate the main JS file
worker.terminate();
// stop the worker from the worker code.
self.close();
【讨论】: