System.Threading.Timer的正确使用
我偶然发现了一些类似于下面的代码:
private void SomeCallBack(object state)
{
lock (_lock)
{
try
{
if (_timer == null)
return;
_timer.Dispose();
// do some work here
}
catch
{
// handle exception
}
finally
{
_timer = new Timer(SomeCallBack, state, 100, Timeout.Infinite);
}
}
}
我不明白每次执行回调时重新创建计时器的目的。我认为代码试图实现的目标是一次只有一个线程可以执行工作。但锁还不够吗?
另外,根据msdn,
请注意,调用 Dispose() 方法重载后可能会发生回调
这样做有什么好处吗? 如果是这样,其好处是否足以证明处理和创建计时器的开销是合理的?
感谢您的帮助。
I stumbled across some code similar to below:
private void SomeCallBack(object state)
{
lock (_lock)
{
try
{
if (_timer == null)
return;
_timer.Dispose();
// do some work here
}
catch
{
// handle exception
}
finally
{
_timer = new Timer(SomeCallBack, state, 100, Timeout.Infinite);
}
}
}
I don't understand the purpose of recreating the timer every time the callback is executed. I think what the code is trying to achieve is that only one thread can perform the work at a time. But wouldn't the lock be sufficient?
Also, according to msdn,
Note that callbacks can occur after the Dispose() method overload has been called
Is there any benefits of doing this?
If so, do the benefits justify the overheads in disposing and creating the timer?
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码似乎需要一个接近周期性的计时器(不完全是周期性的,因为计时器到期和新计时器创建之间的处理引入了抖动)。处理和重新创建计时器确实是不必要的开销。
Change
方法会更好。对 null 的检查也很奇怪;在其他地方,必须有代码将
_timer
设置为 null 才能产生任何效果。It seems that the code wants a nearly periodic timer (not exactly periodic because of the jitter introduced by the processing between the expiration of the timer and creation of the new timer). Disposing and recreating the timer is indeed an unnecessary overhead. The
Change
method would be better.The check for null is also curious; somewhere else there would have to be code that sets
_timer
null for it to have any effect.重新创建计时器的原因是针对计时器回调中的代码执行时间比计时器周期长的情况。在这种情况下,回调的多个实例将同时运行。
The reason for recreating the timer would be for the scenario where the code in the timer callback takes longer to execute than the timer period. In this case multiple instances of the callback would be running at the same time.