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

I want to save the state of the widget if it has not been changed within 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 allows you to add a new timer if it is already running, but not reset the timer that is already running. I looked through the docs and I cannot figure out how to do this. How to reset the timer?

+3
source share
1 answer

I believe that you can use GLib.Source.Remove to remove the event source that GLib.Timeout.Add will return to you when you need to re-initialize the timer. Pls see if the code below will work:

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;
    });
};

System.Timers.Timer. Smth :

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();
    }
};

, ,

+4

Source: https://habr.com/ru/post/1727065/


All Articles