[英]Stop/Restart GLib.Timeout.Add();
This function starts a timer in GTK#. 该功能在GTK#中启动一个计时器。 I want to be able to start and stop this as I please.
我希望能够根据需要启动和停止此操作。
void StartClock ()
{
GLib.Timeout.Add (1000, new GLib.TimeoutHandler (AskPython));
}
Glib timeout doesn't support that but here is a timer class I wrote that mimics Microsoft's timer class. Glib超时不支持该功能,但是我写的这是一个模仿Microsoft计时器类的计时器类。
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;
}
}
Usage: 用法:
Timer t = new Timer (1000);
t.TimerElapsedEvent += (sender, args) => {
Console.WriteLine (args.signalTime.ToString ());
};
t.enabled = true;
You can use a global variable to disable that could be checked within AskPython
function and do nothing if it is set. 您可以使用全局变量来禁用可在
AskPython
函数中检查的全局变量,如果设置了该变量则什么也不做。
Otherwise, which I think is the right way for GLib. 否则,我认为这是GLib的正确方法。
AskPython
should return false
. AskPython
应该返回false
。
The function is called repeatedly until it returns False, at which point the timeout is automatically destroyed and the function will not be called again.
重复调用该函数,直到返回False,这时超时将自动销毁,并且不会再次调用该函数。
Reference: glib.timeout_add 参考: glib.timeout_add
Then call GLib.Timeout.Add
if you want to enable it again. 如果要再次启用它,请调用
GLib.Timeout.Add
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.