Electron的IPC通讯 send/on 和 invoke/handle 的区别
整理一个 对比表,一眼能看出 send/on
和 invoke/handle
的区别:
🚦 Electron IPC 对比表
特性 | ipcRenderer.send + ipcMain.on | ipcRenderer.invoke + ipcMain.handle |
---|---|---|
通信模式 | 单向消息,渲染进程 → 主进程 | 请求-响应,渲染进程 ↔ 主进程 |
返回值 | 无(需要 event.reply 或再发消息返回) | 有(返回 Promise ,主进程可以 return 结果) |
使用场景 | - 事件通知 - 状态更新 - 不关心返回值 | - 需要等待结果 - 类似 API 调用 - 异步操作(文件读写、网络请求) |
主进程写法 | js ipcMain.on('channel', (event, args) => { console.log(args); event.reply('channel-reply', {ok: true}); }); | js ipcMain.handle('channel', async (event, args) => { console.log(args); return {ok: true}; }); |
渲染进程写法 | js ipcRenderer.send('channel', {foo: 1}); ipcRenderer.on('channel-reply', (e, res) => console.log(res)); | js const res = await ipcRenderer.invoke('channel', {foo: 1}); console.log(res); |
重复绑定风险 | 高,如果 ipcMain.on 多次注册同一 channel,会多次触发 | 低,ipcMain.handle 同一 channel 会覆盖旧的 handler |
是否能用 send() | ✅ 必须用 | ❌ 必须用 invoke() |
是否能返回值 | ❌(需要额外 reply 或 send 回去) | ✅(直接 return ,渲染进程拿到结果) |
🔑 总结
- 只发消息,不需要结果 → 用
send/on
- 要拿结果,像调用 API → 用
invoke/handle
本章完!