[Gtk-sharp-list] GLib.Timerout How to use?

Michael Hutchinson m.j.hutchinson at gmail.com
Sat Sep 13 23:36:49 EDT 2008

On Sat, Sep 13, 2008 at 10:33 PM, True Friend <true.friend2004 at gmail.com> wrote:
> Hi
> I want to add a timer in gtk(#) application to autosave text in textview. I
> had used System.Timers.Timer while working on windows (on same application).
> In gtk i am unable to find a way to get it done. I tried
> System.Timers.Timer.Tick but it wasn't there in mono class library. I then
> tried System.Timers.Timer.Elapsed but it won't worked. I then advised to use
> GLib.Timeout. It also doesn't work. The problem which occurs (even with
> System.Timers.Timer.Elapsed) is that when I click on the Action (menu item)
> the gui freezes simply without any progress. Plz suggest me where I am

You are probably trying to access non-threadsafe objects from the
wrong thread. In general GTK# classes can only be accessed from the
GUI thread. I belive that System.Timers.Timer uses a separate thread
for its callbacks.

Please see http://www.mono-project.com/Responsive_Applications for more info.

Note that GLib.Timeouts are invoked in the GTK thread, but you may
need to call Gdk.Threads.Enter () ay the start of the timeout and
Gdk.Threads.Leave () at the end to ensure it works on Windows.

> wrong. Here is the code I am trying to use behind a menu item toggle
> (event).
> --------------------------
> protected virtual void OnAction19Toggled (object sender, System.EventArgs e)
>     {
>         if(this.Action19.Active == true)
>         {
>             while(this.Action19.Active)

You have an infinite loop.

>             {
>                 GLib.Timeout.Add(1000, new
> GLib.TimeoutHandler(AutoSaveEventHandler));
>             }
>         }
>     }

What you need is something like:

bool autoSaveEnabled = false;

protected virtual void OnAction19Toggled (object sender, System.EventArgs e)
    //if mode has changed
    if (this.autosaveEnabled !=  this.Action19.Active) {

        //set flag -- the AutoSaveHandler uses this to disable itself
        this.autoSaveEnabled = this.Action19.Active;

        //and is enabled, start the handler
        if (this.autoSaveEnabled ) {
            //this will be run every 1000ms until it returns false
            GLib.Timeout.Add (1000, GLib.TimeoutHandler (AutoSaveHandler ));

bool AutoSaveHandler ()
    if (autoSaveEnabled) {
        AutoSave ();
        return true;
    } else {
        return false;

Michael Hutchinson

More information about the Gtk-sharp-list mailing list