electron中ipcRenderer.invoke、ipcRenderer.on、ipcRenderer.send、ipcRenderer.sendSync作用与区别
IPC 渲染进程与主进程通信方法解析
ipcRenderer
的这几个方法作用不完全相同 ,它们适用于不同的通信场景,核心区别在于通信方向 、是否需要响应 以及同步 / 异步特性。下面详细说明:
1. ipcRenderer.send(channel, ...args)
-
作用 :从渲染进程 向主进程 发送异步消息(单向通信),不需要返回结果。
-
特点:
-
发送后立即返回,不等待主进程处理。
-
主进程通过
ipcMain.on(channel, (event, ...args) => { ... })
接收。 -
适合只需要通知主进程执行操作,不需要结果的场景。
-
-
示例:
// 渲染进程
ipcRenderer.send('open-file', '/path/to/file');
// 主进程
ipcMain.on('open-file', (event, path) => {
fs.openSync(path, 'r');
});
2. ipcRenderer.on(channel, listener)
-
作用 :在渲染进程 中监听主进程发送的特定频道消息(被动接收)。
-
特点:
-
用于接收主进程通过
webContents.send(channel, ...args)
发送的消息。 -
是 "接收消息" 的方法,而非 "发送消息"。
-
-
示例:
// 渲染进程(监听主进程消息)
ipcRenderer.on('file-opened', (event, content) => {
console.log('文件内容:', content);
});
// 主进程(发送消息给渲染进程)
mainWindow.webContents.send('file-opened', '文件内容...');
3. ipcRenderer.invoke(channel, ...args)
-
作用 :从渲染进程 向主进程 发送异步请求 ,并等待主进程返回结果(类似 HTTP 的请求 - 响应模式)。
-
特点:
-
返回一个
Promise
,可配合async/await
使用。 -
主进程通过
ipcMain.handle(channel, async (event, ...args) => { ... })
处理并返回结果。 -
适合需要主进程处理后返回数据的场景(如读取文件、调用系统 API 等)。
-
-
示例:
// 渲染进程
async function readFile() {
const content = await ipcRenderer.invoke('read-file', '/path/to/file');
console.log('文件内容:', content);}
// 主进程
ipcMain.handle('read-file', async (event, path) => {
return fs.readFileSync(path, 'utf8'); // 返回结果给渲染进程
});
4. ipcRenderer.sendSync(channel, ...args)
-
作用 :从渲染进程 向主进程 发送同步请求 ,会阻塞渲染进程直到主进程返回结果。
-
特点:
-
同步执行,会卡住渲染进程(可能导致界面卡顿),不推荐频繁使用。
-
主进程通过
ipcMain.on(channel, (event, ...args) => { event.returnValue = ... })
返回结果。 -
适合极少数必须同步获取结果的场景。
-
-
示例:
// 渲染进程(同步等待结果)
const content = ipcRenderer.sendSync('read-file-sync', '/path/to/file');
console.log('文件内容:', content);
// 主进程
ipcMain.on('read-file-sync', (event, path) => {
event.returnValue = fs.readFileSync(path, 'utf8'); // 通过 returnValue 返回
});
核心区别总结
方法 | 通信方向 | 同步 / 异步 | 是否需要返回结果 | 主进程处理方式 |
---|---|---|---|---|
send |
渲染 → 主进程 | 异步 | 不需要 | ipcMain.on |
on |
主进程 → 渲染 | 异步 | 接收结果 | 配合 webContents.send |
invoke |
渲染 → 主进程 | 异步 | 需要(请求 - 响应) | ipcMain.handle |
sendSync |
渲染 → 主进程 | 同步 | 需要(阻塞) | ipcMain.on + event.returnValue |
最佳实践
-
大多数场景优先使用
invoke
(异步请求 - 响应)和send
(单向通知)。 -
避免使用
sendSync
,因其会阻塞渲染进程,影响用户体验。 -
主进程向渲染进程发送消息时,用
webContents.send
配合渲染进程的ipcRenderer.on
。