System.Timers.Timer vs System.Threading.Timer

后端 未结 8 1944
情书的邮戳
情书的邮戳 2020-11-22 07:08

I have been checking out some of the possible timers lately, and System.Threading.Timer and System.Timers.Timer are the ones that look needful to me (since they support thre

相关标签:
8条回答
  • 2020-11-22 08:12

    System.Threading.Timer is a plain timer. It calls you back on a thread pool thread (from the worker pool).

    System.Timers.Timer is a System.ComponentModel.Component that wraps a System.Threading.Timer, and provides some additional features used for dispatching on a particular thread.

    System.Windows.Forms.Timer instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.

    If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer is as good as it gets in the framework.

    I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:

    1. it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety

    2. re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor

    0 讨论(0)
  • 2020-11-22 08:12

    In his book "CLR Via C#", Jeff Ritcher discourages using System.Timers.Timer, this timer is derived from System.ComponentModel.Component, allowing it to be used in design surface of Visual Studio. So that it would be only useful if you want a timer on a design surface.

    He prefers to use System.Threading.Timer for background tasks on a thread pool thread.

    0 讨论(0)
提交回复
热议问题