該函數在GTK#中啓動一個定時器。我希望能夠隨心所欲地啓動和停止。停止/重新啓動GLib.Timeout.Add();
void StartClock()
{
GLib.Timeout.Add (1000, new GLib.TimeoutHandler (AskPython));
}
該函數在GTK#中啓動一個定時器。我希望能夠隨心所欲地啓動和停止。停止/重新啓動GLib.Timeout.Add();
void StartClock()
{
GLib.Timeout.Add (1000, new GLib.TimeoutHandler (AskPython));
}
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;
您可以使用全局變量來禁用可能AskPython
函數中進行檢查,如果設置什麼也不做。
否則,我認爲這是GLib的正確方法。 AskPython
應返回false
。
該函數被重複調用,直到它返回False,此時超時被自動銷燬,函數將不會再被調用。
然後調用GLib.Timeout.Add
如果您想再次啓用它。