停止/重启GLib.Timeout.Add();

时间:2014-07-11 13:23:26

标签: c# multithreading mono glib gtk#

此功能在GTK#中启动计时器。我希望能够随心所欲地开始和停止这一点。

void StartClock ()
 {
    GLib.Timeout.Add (1000, new GLib.TimeoutHandler (AskPython));
 }

2 个答案:

答案 0 :(得分:2)

Glib超时并不支持,但这里是我编写的模拟微软计时器类的计时器类。

public delegate void TimerElapsedHandler (object sender, TimerElapsedEventArgs args);

public class TimerElapsedEventArgs : EventArgs
{
    DateTime signalTime;

    public TimerElapsedEventArgs () {
        signalTime = DateTime.Now;
    }
}

public class Timer
{
    private bool _enabled;
    public bool enabled {
        get {
            return _enabled;
        }
        set {
            _enabled = value;
            if (_enabled)
                Start ();
            else
                Stop ();
        }
    }
    protected uint timerId;

    public event TimerElapsedHandler TimerElapsedEvent;
    public uint timerInterval; 
    public bool autoReset;

    public Timer () : this (0) { }

    public Timer (uint timerInterval) {
        _enabled = false;
        this.timerInterval = timerInterval;
        autoReset = true;
        timerId = 0;
    }

    public void Start () {
        _enabled = true;
        timerId = GLib.Timeout.Add (timerInterval, OnTimeout);
    }

    public void Stop () {
        _enabled = false;
        GLib.Source.Remove (timerId);
    }

    protected bool OnTimeout () {
        if (_enabled) {
            if (TimerElapsedEvent != null)
                TimerElapsedEvent (this, new TimerElapsedEventArgs ());
        }
        return _enabled & autoReset;
    }
}

用法:

Timer t = new Timer (1000);
t.TimerElapsedEvent += (sender, args) => {
    Console.WriteLine (args.signalTime.ToString ());
};
t.enabled = true;

答案 1 :(得分:0)

  • 您可以使用全局变量来禁用可以在AskPython函数中检查的全局变量,如果已设置则不执行任何操作。

  • 否则,我认为这是GLib的正确方法。 AskPython应该返回false

      

    重复调用该函数,直到它返回False,此时超时自动销毁,并且不会再次调用该函数。

    参考: glib.timeout_add

    如果您想再次启用它,请致电GLib.Timeout.Add