问题
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