电子渲染器过程:何时应该清洁IPC侦听器

问题描述

我在渲染器进程ReactJs上有一个Electron应用程序,以及一个Redux基础结构,该接口连接并同步该应用程序所有打开的进程(一个主进程和多个渲染器进程)中的所有商店

Redux同步通信是通过电子IPC实现的,因此我有几个用于不同通道的侦听器,这些侦听器是在每个渲染器进程(浏览器窗口)中添加的

作为示例,下面的代码侦听来自主流程的调度动作:

export const listenToFromMainDispatchedActions = (store: Store,senderId: string): () => void => {
  const listener = (event: IpcRendererEvent,args: any): void => {
    if (!isValidAppAction(args)) {
      appLogger.warn('Received an invalid action form main!!!');
    } else {
      const action: IAppReduxAction<any> = {
        ...args,meta: {
          ...args.meta,handler: ReduxActionHandler.RECEIVER,},};
      if (action.meta.senderId !== senderId) store.dispatch(action);
    }
  };

  ipcRenderer.on(IPCChannels.ACTION_DISPATCH,listener);
  appLogger.warn('STORE_DISPATCH','ADDED ACTION_DISPATCH');
  return (): void => {
    ipcRenderer.removeListener(IPCChannels.ACTION_DISPATCH,listener);
    appLogger.warn('STORE_DISPATCH','REMOVED ACTION_DISPATCH');
  };
};

这段代码在我的index.tsx文件中执行,如下所示:

// index.tsx
// ...
export const GLOBAL_SENDER_ID = uuidV4();
const store = storeCreator({
  level: 'renderer',reducer: renderersReducer,sagas: mainAppWindowSagas,senderId: GLOBAL_SENDER_ID,});

const listenerRemover = listenToFromMainDispatchedActions(store,GLOBAL_SENDER_ID);
...

我的问题是,为了删除IPC侦听器,调用listenerRemover()的最佳方式是什么时候?

我试图捕获beforeunload之类的其他文档/窗口事件,但无济于事。 为了使所有内容保持“平滑”状态,我实际上在应用启动时打开了所需的窗口并隐藏了它们,关闭窗口则将它们隐藏而不是杀死它们,我意识到这是一个有问题的事件,但是我需要一种方法来优雅地删除这些监听器,我发现文档中没有任何帮助

预先感谢

解决方法

所以我想到的解决方案是:

在浏览器端/渲染器进程中(在index.tsx中,我执行以下操作:

// index.tsx (renderer process)
// ...
export const GLOBAL_SENDER_ID = uuidV4();
const store = storeCreator({
  level: 'renderer',reducer: renderersReducer,sagas: mainAppWindowSagas,senderId: GLOBAL_SENDER_ID,});

const listenerRemover = listenToFromMainDispatchedActions(store,GLOBAL_SENDER_ID);

const cleanup = (): void => {
   appLogger.log('WINDOW CLOSING');
   listenerRemover();
   window.removeEventListener('beforeunload',cleanup);
}

window.addEventListener('beforeunload',cleanup)
...

在主要过程中,我删除了所有的ipcMain对应项:

// index.ts
import { app,ipcMain } from 'electron';
import main from './main'
// ....
app.whenReady()
  .then(main)
  .catch((error) => {
    appLogger.error(TAG,error);
  });

// .....
app.on('before-quit',() => {
  Object.values(IPCChannels).forEach(
    (channel) => {
      ipcMain.removeAllListeners(channel);
    }
  );
  appLogger.log('CLEANED ALL IPCS');
  appLogger.log('Done,BYEBYE');
});


它似乎按预期运行,并且我设法在相关位置查看日志,尽管我不确定这种方法的有效性,但我将在几天之内不回答我的问题(今天是13.08.2020 12:15CEST)。

如果我将在一周左右的时间内没有收到其他/更好的答案,我将接受我的答案作为正确的答案。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...