我如何知道网络工作者是否已关闭? [英] How can i know if a web worker has closed?

查看:32
本文介绍了我如何知道网络工作者是否已关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML5 Worker 可以通过调用 close() 方法关闭自己.

HTML5 Workers can close themselves by calling the close() method.

有没有办法判断工作进程是否处于活动状态/正在运行或是否已关闭?

Is there a way to tell if the worker process is alive/running or if it has been closed?

var myWorker = new Worker("worker.js");

...

if( myWorker.isAlive() ) {
    // do stuff
}

推荐答案

worker 本身不会告诉你,但你有两个选择:

The worker itself won't tell you, but you have two options:

  1. 您可以在正在运行的脚本中放入一些内容.例如,布尔值 isRunning:

示例:

function myScript()
{
    isRunning = true;
    ...do stuff...
    isRunning = false;
}

然后在 setIntervalsetTimeout(重复调用 self)中运行一个函数来检查该值.

Then have a function running in setInterval or setTimeout (that calls self repeatedly) that checks for that value.

您还需要处理错误 try...catch,以便在错误结束代码时将其设置为 false.

You'll also want to handle errors try...catch so you can set it to false when an error ends your code.

  1. 您可以使用 postMessage 并向您的脚本发送一个请求,该请求会告诉您它是否仍在运行.
  1. You can use postMessage and send a request to your script that will tell you if it's still running.

示例:

//Make sure we have a listener
myWorker.addEventListener( 'message', checkIsRunning );

//Now ask
myWorker.postMessage( { request: MyWorker.IS_RUNNING } );

//The worker would have something like:
self.onmessage = function (msg) {
    switch (msg.data.aTopic) {
    case MyWorker.IS_RUNNING:
        self.postMessage( { aTopic: isRunning } );
        break;
    default:
        throw 'no aTopic on incoming message to ChromeWorker';
    }
}

请注意,两个选项都不会告诉您 Worker 对象是否已死(不是),因为它总是仍然能够响应消息,直到您调用 terminate();

Note that with both options, neither one tells you whether the Worker object is dead (it's not), as it is always still able to respond to messages until you call terminate();

如果您想在 close() 函数被调用时进行捕获,请在第一次运行时将其保存在您的工作器中:

If you instead want to capture whenever the close() function is called, save that in your worker when it's first run:

myWorker._selfClose = self.close;

然后在覆盖的关闭函数中调用它:

And then call that inside your overridden close function:

close: function()
{
    //Mark it as no longer running
    this.isRunning = false;

    //Call original close function
    this._selfClose();
}

这篇关于我如何知道网络工作者是否已关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆