通过 worker.postMessage() 发送的消息是否排队? [英] are messages sent via worker.postMessage() queued?
问题描述
创建一个worker后,我可以通过postMessage
向它发送消息.例如:
After creating a worker, I can send messages to it via postMessage
. For example:
var worker = new Worker('helper.js');
worker.postMessage({...});
在 helper.js 中,worker 需要使用 onmessage = function (event) { ... };
Inside helper.js, the worker needs to add a listener using onmessage = function (event) { ... };
我的问题是,如果在 worker 脚本仍在加载时向 worker 发送了一条或多条消息,是否可以保证消息最终排队并交付,或者它们可能会丢失?
My question is, if one or more messages are sent to the worker while the worker script is still loading, is it guaranteed that the messages get queued and delivered eventually, or is it possible that they may get lost?
推荐答案
http://www.w3.org/TR/2015/WD-workers-20150924/#communicating-with-a-dedicated-worker 说
专用 worker 使用的隐式 MessagePort 在创建时隐式启用了其端口消息队列
The implicit MessagePort used by dedicated workers has its port message queue implicitly enabled when it is created
还有
https://developer.mozilla.org/en/docs/Web/API/Worker/postMessage 没有提到在发送消息之前必须等待工作人员加载
https://developer.mozilla.org/en/docs/Web/API/Worker/postMessage doesn't mention having to wait for the worker to load before sending messages
在创建无法在缓存中的工作线程后立即测试发布消息http://plnkr.co/edit/jM1qy9lDEFKYhR0TDsKa?p=preview
Testing posting messages immediately after creating a worker that can't be in the cache http://plnkr.co/edit/jM1qy9lDEFKYhR0TDsKa?p=preview
var worker = new Worker('worker.js?' + (new Date()).getTime());
worker.postMessage('');
worker.postMessage('');
工作人员只是输出到控制台
with the worker just outputting to the console
self.onmessage = function() {
console.log('received');
}
在测试时总是向我显示 2 条控制台消息.虽然这并不能保证它总是以这种方式工作,但鉴于我试图让它丢失消息并失败,这是合理的证据.
has always shown 2 console messages for me when testing. This isn't a guarantee that it will always work this way though, but given that I'm trying to make it lose messages and failing, it is reasonable evidence.
这篇关于通过 worker.postMessage() 发送的消息是否排队?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!