self.close 是否真的终止了 Web 工作线程?

Does self.close actually kill the web worker thread?

看这个例子:

// CLOSEWORKER.JS:

self.postMessage('foo');
self.close();
self.postMessage('bar');
setTimeout(() => self.postMessage('baz'), 0);

// MAIN.JS:

const worker = new Worker('./worker.js');
worker.onmessage = ({data}) => console.log(data);

即使我调用了 self.close(),下一行 self.postMessage('bar'); 仍然执行并记录 'bar'。我无法理解,因为关闭方法应该只是终止工作线程被调用之后。

另外,再看一个例子:

TERMINATEWORKER.JS:

self.onmessage = ({data}) => console.log(data);

MAIN.JS:

const worker = new Worker('./worker.js');
setTimeout(() => {
 worker.postMessage('foo');
 worker.terminate();
 worker.postMessage('bar');
 setTimeout(() => worker.postMessage('baz'), 0);
}, 1000)

当使用 terminate 方法而不是 close 方法时,代码按预期执行。它只记录 'foo',不记录任何其他内容,这表明线程在调用 terminate 方法后立即被终止。

WorkerGlobalScope.close() when called discards any tasks that have been scheduled and sets the closing WorkerGlobalScope 的标志,有效防止任何新任务排队。

但是,它不会停止当前任务的执行。

所以实际上,在您的第一个示例中,它将 运行 当前脚本直到结束并仍然执行 self.postMessage('bar') 操作,您的主线程将能够处理。

另一方面,

Worker.terminate() 也将“[a]终止当前 运行 正在工作的脚本。”