简体   繁体   English

如何在JavaScript中的线程之间进行通信?

[英]How do I communicate between threads in JavaScript?

I created an XPCOM object in C++ for a FireFox extension. 我用C ++为FireFox扩展创建了XPCOM对象。 I'm using a worker thread to listen for an event and when it happens, I need to do stuff on the main thread. 我正在使用工作线程来侦听事件,当事件发生时,我需要在主线程上做一些事情。 Obviously, I can't just sit and wait in JavaScript on the main thread because you need to be able to use the browser (my event happens very rarely). 显然,我不能只是在主线程中坐在JavaScript中等待,因为您需要能够使用浏览器(我的事件很少发生)。

I tried doing this in the thread (xpcom guy sends javascript an event): 我尝试在线程中执行此操作(xpcom家伙向javascript发送了一个事件):

window.setTimeout( myImportantWorkFunction, 100 );

This works (on the main thread, as intended), but it will pause indefinately. 这可以正常工作(按预期在主线程上进行),但是会无限期地暂停。 it doesn't happen after 100ms as intended. 它不会在预期的100毫秒后发生。 You have to click around a bit or resize the window and then suddenly the function gets called. 您必须单击一下或调整窗口大小,然后突然调用该函数。 Like JavaScript suddenly woke up. 就像JavaScript突然醒了一样。 I assume this is because it's happening in a thread. 我认为这是因为它是在线程中发生的。

Is there some better way for the worker to ask the main thread to do something? 工作者是否有更好的方法要求主线程做某事?

JavaScript only has one thread. JavaScript只有一个线程。 Function calls always block until they return. 函数调用始终阻塞,直到它们返回。 If you are communicating from JS to the browser (or extension of the browser in this case), you should make sure your browser-side code returns to the JS immediately, and remember a callback to invoke when your work completes (this is how setTimeout works). 如果要从JS与浏览器进行通信(在这种情况下为浏览器的扩展名),则应确保浏览器端代码立即返回JS,并记住在工作完成时要调用的回调(这是setTimeout的方式)作品)。

I suspect the "clicking around" is just a coincidence. 我怀疑“点击”只是一个巧合。 Have you tried alerting as soon as the event is fired? 事件触发后,您是否尝试过警报?

For those that care, I gave up on trying to message between threads. 对于那些关心的人,我放弃了尝试在线程之间进行消息传递。 I found a way to compile the XPCOM object with some objective-C++ so that I could use their NSDistributedNotificationCenter. 我找到了一种使用一些Objective-C ++编译XPCOM对象的方法,以便可以使用它们的NSDistributedNotificationCenter。 This lets me get my event on the main thread where javascript is happy. 这使我可以在javascript满意的主线程上获取事件。

The question is still valid but I probably won't take the time to validate anybody's answer now... 这个问题仍然有效,但我现在可能不会花时间验证任何人的答案...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM