System.Threading.Timer检查是否正在运行

时间:2016-11-02 08:51:30

标签: c# timer

有没有办法检查System.Threading.Timer是否正在运行。例如:

private Timer m_timer = new Timer( OnTimerCallback );

private void EnsureTimer()
{
    if( some check if timer is not running )
    {
        m_timer.Change( 30000, Timeout.Infinite );
    }
}

我应该放什么而不是some check if timer is not running

2 个答案:

答案 0 :(得分:0)

您可以跟上计时器时间,并检查它是否等于Timeout.Infinite

int interval = Timeout.Infinite;
int timerCount = 0;
Timer t;
void Main()
{
    interval = 100;
    t = new Timer(OnTick, null, 0, interval);
}

void OnTick(object state)
{
    timerCount++;
    if (timerCount == 3)
    {
        interval = Timeout.Infinite;
        t.Change(Timeout.Infinite, interval);
    }

    $"Timer count: {timerCount}. Timer is running: {IsTimerRunning()}.".Dump();
}

bool IsTimerRunning()
{
    return interval != Timeout.Infinite;
}

/* Output:
Timer count: 1. Timer is running: True.
Timer count: 2. Timer is running: True.
Timer count: 3. Timer is running: False.
*/

答案 1 :(得分:-1)

您应该使用来自System.Timers dll的计时器(不是System.Threading dll),然后轻松使用 .Enabled和.Elapsed 等方法来完成您的功能

此外,线程安全