如何检查启用/禁用定时器?

时间:2015-10-07 10:58:47

标签: c# if-statement timer

我尝试了以下但它不会为我工作。

if (MyTimer.Enabled)
{
    continue;
}
else 
{
    break;
}

如果计时器结束,我想打破for循环。

1 个答案:

答案 0 :(得分:0)

你可以打破你的循环,如下所示。一旦计时器时间结束,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