我想在 2 秒内未编辑小部件后保存它的状态。现在,我的代码看起来像这样:
bool timerActive = false;
...
widget.Changed += delegate {
if (timerActive)
return;
timerActive = true;
GLib.Timeout.Add (2000, () => {
Save ();
timerActive = false;
return false;
});
};
如果一个定时器已经在运行,这会阻止添加一个新的定时器,但不会重置已经在运行的定时器。我查看了文档,但似乎无法找到实现此目的的好方法。如何重置计时器?
最佳答案
我相信您可以使用 GLib.Source.Remove 删除事件源,当您需要重新初始化计时器时,事件源将由 GLib.Timeout.Add 返回给您。请查看以下代码是否适合您:
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 对象。像这样:
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();
}
};
希望这对你有帮助,问候
关于c# - 在 Gtk# 中,如何重置使用 GLib.Timeout.Add 设置的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1989902/