tags:

views:

48

answers:

1

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?

+1  A: 

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

serge_gubenko
GLib.Source.Remove is what I needed. Thanks!
Matthew