如何通过该计时器的回调函数更改 System.Threading.Timer 中的间隔时间?
如何通过该计时器的回调函数更改 System.Threading.Timer 中的时间间隔? 这是正确的吗?
这样做。没有发生。
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));
}
}
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));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此行生成无限递归:
第一个参数强制
TimerCallBack
立即执行。所以它会无限期地一次又一次地执行它。解决办法是
This line generate infinite recursion:
The first parameter forces
TimerCallBack
to execute right away. So it executes it again and again indefinitely.The fix would be
问题是您对
Change
的调用指定下一个调用应该立即发生。如果您要每次调用Change
,则只需使用一段时间Timeout.Infinite
(这只是 -1 的常量)告诉它完全避免重复下一次之后 - 但它仍然会继续触发,因为下一次,你重置了它。例如:或者,您可以只更改一次,然后保留它:
请注意,在任何一种情况下都不会使用初始间隔(上面示例中的 1 秒),因为我们正在调用
Change
立即 - 如果您确实希望在第一次调用之前使用不同的时间,请不要在对Change
的初始调用中使用TimeSpan.Zero
。The problem is that your call to
Change
specifies that the next call should happen immediately. If you're going to callChange
every time, you can just use a period ofTimeout.Infinite
(which is just a constant of -1) to tell it to avoid repeating at all after the next time - but it will still keep firing, because that next time, you reset it. For example:Alternatively, you could change it just once, and then leave it:
Note that nothing is using the initial interval (1 second in the samples above) in either case, because we're calling
Change
immediately - if you really want a different time before the first call, don't useTimeSpan.Zero
in the initial call toChange
.