System.Threading.Timer的正确使用

发布于 2024-10-22 04:29:19 字数 752 浏览 2 评论 0原文

我偶然发现了一些类似于下面的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不顾 2024-10-29 04:29:19

代码似乎需要一个接近周期性的计时器(不完全是周期性的,因为计时器到期和新计时器创建之间的处理引入了抖动)。处理和重新创建计时器确实是不必要的开销。 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.

桃扇骨 2024-10-29 04:29:19

重新创建计时器的原因是针对计时器回调中的代码执行时间比计时器周期长的情况。在这种情况下,回调的多个实例将同时运行。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文