JavaScript Web Worker - close()vs terminate()

时间:2015-05-28 08:16:45

标签: web-worker

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

我何时会使用其中一个?

4 个答案:

答案 0 :(得分:39)

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

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

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

答案 1 :(得分:1)

在React中使用Web Worker时的其他区别:

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

close的问题是,如果要在unmount组件时杀死该工作程序,则需要synchronously,否则,may会得到一个警告,尤其是当您尝试清理ComponentWillUnmount生命周期挂钩或useEffect挂钩中的内容时(否则,将有多个处于活动状态的僵尸Web Worker实例)。

警告看起来像:

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.

OR:

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.

答案 2 :(得分:0)

确实 close()函数可以在Worker的范围内看到。

从外部可以看到

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

TBH起初有点令人困惑,但一旦实施,你就会习惯它

答案 3 :(得分:0)

我发现终止时self.close()很好的用例。在我的网络工作者中,我有一个setInterval函数,该函数正在接收并回传对象位置。使用终止会永久杀死网络工作者,因此我无法将播放消息发送回该工作者。同时关闭它,让我重新打开它并重新启动计时器。

相关问题