Correct Usage Of System.Threading.Timer
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.
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.
精彩评论