[Gtk-sharp-list] GLib Timeout and garbage collection clarification
m.j.hutchinson at gmail.com
Sun Feb 20 20:56:12 EST 2011
On Sun, Feb 20, 2011 at 9:57 AM, Nicholas Frechette <zeno490 at gmail.com> wrote:
> Looking at GLib.Timeout, there is only an Add function, no remove/delete.
> If I have a gui element that creates a timeout to be called repeatedly at an
> interval and eventually that widget is garbage collected, what happens to
> the timeout handler? Will it still be called? Is there a guard internally
> for this?
> ie in pseudo code:
> class Foo : Widget
> public Foo() : base()
> GLib.Timeout.Add(1000, Bar);
> private bool Bar()
> SomeLabel.Text = DateTime.Now.ToString(); // Is this always safe?
> SomeLabel might have been GCed if "this" has been GCed as well?
> return true; // ???
> Should I override dispose, set a flag that is checked in the handler and
> return false then? Is that safe? Will the object still be "live" when the
> handler next attempts to fire? Is the GTK underlying system smart enough to
> detect that the handler's source has been GCed and thus should be removed
> The documentation is very silent about this.
GTK# internally keeps all added handlers in an ArrayList on a static
field. If the function returns false, or you call GLib.Source.Remove
with the handler's ID, then the handler will be removed, so GTK# will
remove it from the list. Keeping a reference to an instance delegate
keeps it alive, so your managed object will not be GC'd as long as the
handler is registered.
However, the GTK+ widget could be destroyed, so you should probably
keep the ID you get from GLib.Timeout.Add in a field, override the
OnDestroyed method, and pass the timeout's ID to GLib.Source.Remove.
More information about the Gtk-sharp-list