如何通过此计时器的回调函数更改System.Threading.Timer中的间隔时间?
问题描述:
如何通过此计时器的回调函数更改System.Threading.Timer中的间隔?这是正确的吗?
How do I change the interval in System.Threading.Timer from the callback function of this timer? Is this correct?
这样做.没发生.
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));
}
}
答
此行生成无限递归:
if(true)
_timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(10));
第一个参数强制 TimerCallBack
立即执行.因此它会无限期地执行它.
The first parameter forces TimerCallBack
to execute right away. So it executes it again and again indefinitely.
解决方法是
if(true)
_timer.Change(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));