【问题标题】:In Gtk#, how do I reset a timer that was set with GLib.Timeout.Add?在 Gtk# 中,如何重置使用 GLib.Timeout.Add 设置的计时器?
【发布时间】:2010-01-01 22:39:33
【问题描述】:

我想在 2 秒内未编辑小部件后保存它的状态。现在,我的代码看起来像这样:

bool timerActive = false;

...

widget.Changed += delegate {
    if (timerActive)
        return;
    timerActive = true;
    GLib.Timeout.Add (2000, () => {
        Save ();
        timerActive = false;
        return false;
    });
};

如果一个新的计时器已经在运行,这会阻止添加一个新的计时器,但不会重置已经在运行的计时器。我浏览了文档,但似乎无法找到实现此目的的好方法。如何重置计时器?

【问题讨论】:

    标签: c# gtk timer gtk#


    【解决方案1】:

    我相信您可以使用 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();
        }
    };
    

    希望这会有所帮助,问候

    【讨论】:

    • GLib.Source.Remove 是我需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 2010-10-02
    • 2021-09-22
    • 2011-06-03
    相关资源
    最近更新 更多