[英]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. 我想在未编辑2秒后保存小部件的状态。 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. 我相信你可以使用GLib.Source.Remove来删除当你需要重新初始化计时器时由GLib.Timeout.Add返回给你的事件源。 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. 作为替代方案,您可以使用System.Timers.Timer对象。 Smth like this: 像这样的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();
}
};
hope this helps, regards 希望这有帮助,问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.