c# - 在 Gtk# 中,如何重置使用 GLib.Timeout.Add 设置的计时器?

标签 c# gtk timer gtk#

我想在 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/

相关文章:

使用 gtk2 创建和存储图像?

javascript - 即使用户不在页面上也可以跟踪计时器

c++ - Allegro:为什么要等待一个事件或直到 60 毫秒结束?

c# - 为什么 .NET System.IO.File 使用 Create/Open 而不是构造函数?

c# - 是否有任何用于命名实体识别的 c# 库?

c# - WinForms CheckedListBox勾选项数的确定

c - 将 Gif 加载到 Gtk3 Window\C++

c# - 编译器错误消息: CS0246: The type or namespace name could not be found

python - 如何确定 Windows、Linux 和 MacOS 中 Python 的显示空闲时间?

java - 试图将代码 move 到 main - Java