【发布时间】:2017-01-10 04:20:05
【问题描述】:
我有一个 Gtk.Box 的子类,其中包含一个 GLib.Timer,它会在给定的时间间隔后触发通知。我在这个类中有调用 Gtk.Box 上的 this.destroy() 的方法。即使在其父实例已被销毁后,计时器仍会继续运行并触发通知。已销毁的此类的所有实例都表现出此行为并继续使用 CPU 和内存,直到进程被杀死。
我该如何解决这个问题?如何有效地杀死实例以及如何手动释放内存而不是依赖 vala 的垃圾收集。
编辑:这是一个(令人尴尬的)mvce
// mvce_deletable
// nine
// 2017.01.11
// valac --pkg gtk+-3.0 --pkg glib-2.0 deletablebox.vala
using Gtk;
using GLib;
class RemovableBox : Gtk.Box {
private Gtk.Button delete_button;
private GLib.Timer timer;
private Gtk.Label label;
public RemovableBox () {
delete_button = new Gtk.Button.with_label ("DESTROY");
delete_button.clicked.connect (()=>{this.destroy();});
this.add (delete_button);
label = new Gtk.Label ("0000000");
this.add (label);
timer = new GLib.Timer ();
timer.start ();
Timeout.add (50, update);
this.show_all ();
}
private bool update () {
if (timer.elapsed () > 10.0f) {
stdout.printf("and yet it breathes\n");
}
label.set_text ("%f".printf(timer.elapsed()));
return true;
}
}
int main ( string [] args ) {
Gtk.init(ref args);
var window = new Gtk.Window ();
window.destroy.connect (Gtk.main_quit);
var delete_me = new RemovableBox ();
window.add ( delete_me );
window.show_all();
Gtk.main();
return 0;
}
我在 RemovableBox 类中添加了一个 timer_id,但它仍然无法正常工作。
class RemovableBox : Gtk.Box {
private Gtk.Button delete_button;
private uint timeout_id;
private GLib.Timer timer;
private Gtk.Label label;
public RemovableBox () {
delete_button = new Gtk.Button.with_label ("DESTROY");
delete_button.clicked.connect (()=>{this.destroy();});
this.add (delete_button);
label = new Gtk.Label ("0000000");
this.add (label);
timer = new GLib.Timer ();
timer.start ();
timeout_id = Timeout.add (40, update);
this.show_all ();
}
~ RemovableBox () {
Source.remove (timeout_id);
}
private bool update () {
if (timer.elapsed () > 10.0f) {
stdout.printf("and yet it breathes\n");
}
label.set_text ("%f".printf(timer.elapsed()));
return true;
}
}
【问题讨论】: