产生一名专职工人的共享工人

产生一名专职工人的共享工人

本文介绍了产生一名专职工人的共享工人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩WebWorkers。不知怎的,我有想法让页面的不同实例知道何时关闭另一个页面。因此,我写了一个共享工作者,它工作正常。

I'm playing around with WebWorkers. Somehow I had the idea to let the different instances of a page know when another one is closed. Therefore I wrote a Shared Worker and it works fine.

但现在我希望一个专用工作者充当共享工作者的接口。因此,UI中昂贵的操作不会影响与Shared Worker的持续通信。
但我收到错误,没有定义SharedWorker。一个想法是使用MessageChannel,但我希望它至少在Firefox和Chrome中运行,据我所知,Firefox仍然没有MessageChannel的工作实现。

But now I want a Dedicated Worker to act as an interface to the Shared Worker. So that expensive actions in the UI won't affect the continous communication with the Shared Worker.But I get the error, SharedWorker was not defined. An idea would be to use MessageChannel, but I want it to run at least in Firefox and Chrome and as far I know, Firefox still doesn't have a working implementation of MessageChannel.

那么 - 这个问题是否有解决办法?

So - are there any workarounds for this problem?

推荐答案

您无法在专用工作程序中创建共享工作程序对象。但是,您可以在主UI线程中创建共享工作器并将其端口传递给专用工作器,以便它们可以直接通信。

You can't create a shared worker object in the dedicated worker. However, you can create a shared worker in the main UI thread and pass its port to the dedicated worker, so they can communicate directly.

例如,在主线程中创建两个worker,并将共享的 port 对象转移到专用对象:

As an example, in main thread create both workers, and transfer the port object of the shared to the dedicated:

var sharedWorker = new SharedWorker("worker-shared.js");
sharedWorker.port.start();

var dedicatedWorker = new Worker("worker-dedicated.js");
dedicatedWorker.postMessage({sharedWorkerPort: sharedWorker.port}, [sharedWorker.port]);

在共享工作人员中,您可以在此端口上发布消息:

In the shared worker you can post messages on this port:

self.onconnect = function(e) {
  var port = e.ports[0];

  self.setInterval(function() {
    port.postMessage('sent from shared worker');
  }, 1000);
};

在专注中你可以对它们做出反应

And in the dedicated you can react to them

self.onmessage = function(e) {
  var sharedWorkerPort = e.data.sharedWorkerPort;
  sharedWorkerPort.onmessage = function(e) {
    console.log('received in dedicated worker', e.data);
  };
};

你可以在

这篇关于产生一名专职工人的共享工人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:43