我有一个系统,在该系统中,我将一个大数组发送到worker中,然后使用库对其进行压缩。压缩需要很长时间,这会使工作人员变得忙碌。我想知道在工作人员仍处于忙碌状态时是否还会收到发送给该工作人员的其他消息。消息会丢失吗?他们也会排队并最终由工人处理吗?
答案 0 :(得分:1)
是的,一旦工作人员完成当前的工作,它将能够处理队列中的下一条消息。这是一个示例:
// https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
// I put in a Stack Snippet for live demonstration
// in a real project, put this in a separate file
const workerFn = () => {
self.onmessage = () => {
self.postMessage('Worker message callback just fired');
// something expensive
for (let i = 0; i < 2e9; i++) {
}
self.postMessage('Expensive operation ending');
};
};
const workerFnStr = `(${workerFn})();`;
const blob = new Blob([workerFnStr], { type: 'text/javascript' });
const worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = ({ data }) => console.log(data);
worker.postMessage(null);
worker.postMessage(null);
这类似于以下想法:单击DOM中的元素时,即使当前事件循环任务完成,即使该任务很昂贵,也会处理该 。
setTimeout(() => {
window.onclick = () => console.log('click callback running');
// something expensive
for (let i = 0; i < 3e9; i++) {
}
console.log('Main synchronous task finishing');
}, 500);
Click here *quickly* after running the snippet