在web worker中生成- setTimeout是否足够,或者我也必须退出

Yielding in a web worker - is setTimeout enough, or must I exit too?

本文关键字:或者 退出 是否 worker web setTimeout      更新时间:2023-09-26

在我的web worker中,我必须在循环中做大量的处理。在c#或Java世界中,我会这样编码(Java):

// main code:
public static void mainLoop() {
    for (Iterator it=getIterator(); it.hasNext() && keepRunning; ) {
        Object item = it.next();
        processThisOne (item);
    }
}
// async method
static boolean keepRunning = true;
public static void abort() {
    keepRunning = false;
}

以上内容在web worker中不起作用。当主循环在上面运行时,后续的postMessage()调用将被处理。

我可以做以下操作(现在在typescript中):

// kicked off by postMessage event handler
public mainLoop () : void {
    if (! keepRunning)
        return;
    Object item = it.next();
    processThisOne (item);
    worker.setTimeout(mainLoop, 0);
}
// also callable by postMessage event handler:
static boolean keepRunning = true;
public static void abort() {
    keepRunning = false;
}

相反,我基本上可以按如下方式生成吗?如果是这样,这是否很快(在setTimeout上线程之间有任务切换)?

// kicked off by postMessage event handler
public mainLoop () : void {
    for (Iterator it=getIterator(); it.hasNext() && keepRunning; ) {
        Object item = it.next();
        processThisOne (item);
        // yield
        worker.setTimeout(nothing, 0);
    }
}
// called by setTimeout:
public static void nothing() {
}
// also callable by postMessage event handler:
static boolean keepRunning = true;
public static void abort() {
    keepRunning = false;
}

如果上面的工作,那么我的代码保持简单。问题是,setTimeout()会产生吗?或者它只是在我当前执行的处理结束后排队调用?

我已经运行了一些测试,我相信答案是您必须退出您所处的方法。setTimeout() queue在方法中启动,但在web worker中没有任何东西在运行之前不会运行它。