0
我嘗試了下面,但它不會爲我工作。如何檢查定時器是否啓用/禁用?
if (MyTimer.Enabled)
{
continue;
}
else
{
break;
}
如果計時器結束,我想打破for
循環。
我嘗試了下面,但它不會爲我工作。如何檢查定時器是否啓用/禁用?
if (MyTimer.Enabled)
{
continue;
}
else
{
break;
}
如果計時器結束,我想打破for
循環。
你可以打破你的循環,如下所述。一旦定時器時間過去,while循環就會中斷。
private static System.Timers.Timer MyTimer;
static bool runningloop;
public static void Main()
{
runningloop=true;
MyTimer = new System.Timers.Timer();
MyTimer.Interval = 2000;
MyTimer.Elapsed += OnTimedEvent;
MyTimer.Enabled = true;
// If the timer is declared in a long-running method, use KeepAlive to prevent garbage collection
// from occurring before the method ends.
//GC.KeepAlive(MyTimer)
while(runningloop)
{
//do your work here
}
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
runningloop=false;
}
參考here
什麼'MyTimer' BTW? – Rahul
您是否將Enabled設置爲true?如果Timer正在運行,則此屬性無關。 MSDN說:「獲取或設置一個值,指示定時器是否應該引發Elapsed事件。」默認爲false – MajkeloDev
我想'MyTimer'是'System.Timers.Timer',你可以使用'OnTimedEvent',當定時器Elapsed時觸發。 –