How do I change the interval time in System.Threading.Timer from the callback function of this timer?

mrbrooks picture mrbrooks · May 25, 2011 · Viewed 17.2k times · Source

How do I change the interval in System.Threading.Timer from the callback function of this timer? Is this correct?

Doing so. Did not happen.

public class TestTimer
{
    private static Timer _timer = new Timer(TimerCallBack); 

    public void Run()
    {
        _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(1));
    }

    private static void TimerCallBack(object obj)
    {
        if(true)
            _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(10));
    }

}

Answer

Alex Aza picture Alex Aza · May 25, 2011

This line generate infinite recursion:

if(true)
    _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(10));

The first parameter forces TimerCallBack to execute right away. So it executes it again and again indefinitely.

The fix would be

if(true)
    _timer.Change(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));