Matthew
Matthew

Reputation: 29216

In Gtk#, how do I reset a timer that was set with GLib.Timeout.Add?

I'd like to save the state of a widget once it has not been editted for 2 seconds. Right now, my code looks something like this:

bool timerActive = false;

...

widget.Changed += delegate {
    if (timerActive)
        return;
    timerActive = true;
    GLib.Timeout.Add (2000, () => {
        Save ();
        timerActive = false;
        return false;
    });
};

This keeps a new timer from being added if one is already running, but does not reset the timer that is already running. I've looked through the docs, and I can't seem to figure out a good way to accomplish this. How do I reset a timer?

Upvotes: 3

Views: 2369

Answers (1)

serge_gubenko
serge_gubenko

Reputation: 20492

I believe you can use GLib.Source.Remove to remove the event source which would be returned to you by GLib.Timeout.Add whenever you need to reinitialize the timer. Pls see if code below would work for you:

private uint _timerID = 0;

widget.Changed += delegate 
{
    if (_timerID>0)
    {
        GLib.Source.Remove(_timerID);               
        _timerID = 0;
    }
    _timerID = GLib.Timeout.Add (2000, () => 
    {                           
        Save();
        _timerID = 0;
        return false;
    });
};

as an alternative you can use System.Timers.Timer object. Smth like this:

System.Timers.Timer _timer = null;

widget.Changed += delegate 
{
    if (_timer==null)
    {
        _timer = new Timer(5000);
        _timer.AutoReset = false;
        _timer.Elapsed += delegate 
        {
            Save(); 
        };
        _timer.Start();
    }
    else
    {
        _timer.Stop();
        _timer.Start();
    }
};

hope this helps, regards

Upvotes: 4

Related Questions