Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
    }

}
like image 866
mrbrooks Avatar asked May 25 '11 05:05

mrbrooks


1 Answers

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));
like image 140
Alex Aza Avatar answered Sep 27 '22 00:09

Alex Aza