Aurelia,Electron:检测到可能的事件发射器内存泄漏
我正在使用electron和aurelia构建一个系统资源监视器作为一个项目 Main.jsAurelia,Electron:检测到可能的事件发射器内存泄漏,electron,aurelia,Electron,Aurelia,我正在使用electron和aurelia构建一个系统资源监视器作为一个项目 Main.js var ramInfo = {}; var result = await si.mem() ramInfo.total = parseInt(result.total / 1024 / 1024); ramInfo.used = parseInt(result.used / 1024 / 1024); ramInfo.percentUsed = parseInt((ramInfo.u
var ramInfo = {};
var result = await si.mem()
ramInfo.total = parseInt(result.total / 1024 / 1024);
ramInfo.used = parseInt(result.used / 1024 / 1024);
ramInfo.percentUsed = parseInt((ramInfo.used / ramInfo.total) * 100);
ramInfo.percentAvailable = parseInt((ramInfo.percentUsed - 100) * -1);
event.sender.send('ram-reply', ramInfo);
})
Overview.js:
async attached () {
await this.getRamInfo();
this.startDataRefresh();
}
async getRamInfo () {
window.ipc.send('ram');
await window.ipc.on('ram-reply', (event, result) => {
this.system.ram = result;
//This line gets logged an additional time each time the setInterval function runs
console.log(this.system.ram);
this.ramData.series = [this.system.ram.percentAvailable, this.system.ram.percentUsed];
new Chartist.Pie('.ram-chart', this.ramData , this.options);
});
console.log("Break");
}
startDataRefresh() {
let scope = this;
setInterval(function() {
scope.getRamInfo();
}, 3000);
}
我在电子控制台中收到以下错误:
MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 ram-reply listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
我认为getRamInfo()函数每三秒运行一次,但是,每次函数运行时,函数的console.log部分都会被额外记录一次。我相当肯定这就是问题所在,我只是不知道为什么它在每个间隔运行多次
编辑:
在将setInterval函数移到main.js中时,我已经找到了部分解决方案:
ipcMain.on('ram', async (event) => {
setInterval(async function() {
var ramInfo = {};
var result = await si.mem()
ramInfo.total = parseInt(result.total / 1024 / 1024);
ramInfo.used = parseInt(result.used / 1024 / 1024);
ramInfo.percentUsed = parseInt((ramInfo.used / ramInfo.total) * 100);
ramInfo.percentAvailable = parseInt((ramInfo.percentUsed - 100) * -1);
event.sender.send('ram-reply', ramInfo)
}, 3000);
})
似乎每次原始setInterval调用ipcMain时,都会创建一个新的侦听器,每次侦听器都会返回结果。我希望它取决于打开的视图,因此最好通过视图进行控制。尝试以下操作:
async getRamInfo () {
window.ipc.send('ram');
return new Promise(resolve => window.ipc.once('ram-reply', (event, result) => resolve(result));
}
async refresh() {
const ramInfo = await this.getRamInfo();
this.ramData.series = [this.system.ram.percentAvailable, this.system.ram.percentUsed];
new Chartist.Pie('.ram-chart', this.ramData , this.options);
// ...
}
startDataRefresh() {
if(!this.interval) {
this.interval = setInterval(() => this.refresh(), 3000);
}
}
stopDataRefresh() {
if(this.interval) {
clearInterval(this.interval);
delete this.interval;
}
}
主要部分-window.ipc.once('ram-reply'
)-使用once
进行一次性事件订阅