已经以多种不同的形式提出了这个问题,但我不确定我的情况是否完全适用。
说,我有一个 node.js 程序。我的程序通过实例化一个名为 Stream 的类连接到一个 Stream。在 Stream 中实例化了一个 StreamParser 类,其中包含几个定时器。
当我Stream.destroy()
的原始流时,保存 StreamParser 的对象设置为null
. 内存空间会发生什么,计时器会发生什么?似乎我的计时器仍在运行,除非我明确表示clearTimeout
它们......
所以,嵌套结构:
new Stream()
-> this.stream = new StreamParser()
-> this.intv = setInterval(function() { // code }, 1000);
// Streams are destroyed like this:
Stream.destroy()
-> calls this.stream.destroy(function() {
self.stream = null;
// stream is null. but timers seem to be running. So, is stream still in memory?
}
我有点困惑。更多扩展的代码示例:
// main call.
var stream = new Stream();
stream.connect();
setTimeout(function() {
stream.destroy(function() {
stream = null;
});
}, 60000);
/** ############# STREAM ############### **/
function Stream() {
this.stream = null;
this.end_callback = null;
}
Stream.prototype.connect = function() {
var self = this;
new StreamParser('stream.com', function(stream) {
self.stream = stream;
self.stream.on('destroy', function(resp) {
if(self.end_callback !== null && typeof self.end_callback === 'function') {
var fn = self.end_callback;
self.end_callback = null;
self.stream = null;
fn();
} else {
self.stream = null;
}
});
});
}
Stream.prototype.destroy = function(callback) {
this.end_callback = callback;
this.stream.destroy();
}
/** ############# STREAM PARSER ############### **/
function StreamParser(uri, callback) {
var self = this;
this.conn = null;
this.callback = null;
this.connectSocket(uri, function(conn) {
self.conn = conn;
self.callback(conn);
})
setInterval(function() {
self.checkHeartbeat();
}, 1000);
}
StreamParser.prototype.checkHeartbeat = function() {
// check if alive
}
StreamParser.prototype.destroy = function() {
this.conn.destroy();
this.emit('destroy', 'socket was destroyed');
}