简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM