Electron 基础教程-6.3 异步IPC通信

Asynchronous IPC Messaging

通常情况下,通过发送IPC消息触发的事件可能会需要很长时间来调用方法,然后返回给渲染进程。这会使渲染进程暂停工作一段时间,很影响应用的用户体验。为了解决渲染器假死的问题,可用异步IPC方法来实现。

首先给index.html<body>内容添加两项:

<button id="sendAsyncMsgBtn">Ping Main Process Async</button>
<p id="asyncReply">Awaiting async response</p>

效果如图6.4所示:
这里写图片描述
Figure 6-4. Our Electron application with the async UI ready

然后在renderer.js中引用这个新按钮:

const asyncMsgBtn = document.getElementById('sendAsyncMsgBtn');

和上一小节一样,为按钮引用添加一个监听器:

asyncMsgBtn.addEventListener('click', function () {

})

注意异步消息的写法有两点和同步消息不同。第一点就是使用send方法代替sendSync:

asyncMsgBtn.addEventListener('click', function () {
    ipc.send('asynchronous-message', 'That’s one small step for man')
})

另一点不同就是:我们要手动写出处理主进程响应的回调函数:

ipc.on('asynchronous-reply', function (event, arg) {
    const message = `Asynchronous message reply: ${arg}`
    document.getElementById('asyncReply').innerHTML = message
})

主进程中的IPC代码也有些改变。监听器整体与之前相同,但是响应函数有变化:用event对象的sender.send方法来替代returnValue

ipc.on('asynchronous-message', function (event, arg) {
    if (arg === 'That’s one small step for man') {
        event.sender.send('asynchronous-reply', ', one giant leap for mankind.')
    }
})

Note
使用不同的channel名可以构造多条IPC消息流

启动应用,点击按钮可以查看异步消息的效果,如图6.5所示:

这里写图片描述
Figure 6-5. Our Electron application, showing the results of our IPC call

扫描二维码关注公众号,回复: 3852815 查看本文章

猜你喜欢

转载自blog.csdn.net/HouszChina/article/details/79619447