Electron: Race condition between main and renderer process

孤人 提交于 2021-01-29 11:17:00

问题


In my Electron application, I am seeing weird behavior. In Windows, sometimes the renderer process executes before the initialization of Electron finishes, which is causing the issue in a startup. For eg: I set up a sequelize database and register IPC channels in the constructor of Main.ts file, so as per my knowledge, app.on('ready') event should be fired once the constructor finishes execution but sometimes in Windows OS only, ready events fires even before the database setup, and my renderer process is calling the database to fetch the default records for the MainWindow.

I think this is a race condition between the renderer process and main process execution, does anyone know how to fix that?

Main.ts

export class Main {
    private mainWindow: BrowserWindow;
    static instance: Main;
    public async init(ipcChannels: IpcChannelInterface[]) {
        Main.instance = this;

        // Registering the IPC Channels
        await this.registerIpcChannels(ipcChannels);

        var config = require('../../package.json');
        app.setAsDefaultProtocolClient(config.build.protocols.name);
        app.setAppUserModelId(config.build.appId);
        app.on('ready', Main.createWindow);
        app.on('window-all-closed', Main.onWindowAllClosed);
        app.on('activate', Main.onActivate);

        //Below statement setup the database
        await SequelizeDB.setup();

    }
}

(new Main()).init([new IpcChannel1(), new IpcChannel2()]);

回答1:


The ready event fires whenever the Electron setup has finished. It has nothing to do with your constructor or init method. From docs:

Emitted once, when Electron has finished initializing

It sounds like you're saying that your createWindow function has a dependency on the database setup function. In that case, you can just do the setup first:

await SequelizeDB.setup();
await app.whenReady(); // this can replace your on("ready", ...) stuff
Main.createWindow();


来源:https://stackoverflow.com/questions/65270268/electron-race-condition-between-main-and-renderer-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!