Is there a timer class in C# that isn't in the Windows.Forms namespace?

后端 未结 6 1266

I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don\'t want to reference this namespace just f

6条回答
  •  隐瞒了意图╮
    2020-12-30 03:48

    This question is old and existing answers cover well the issue as it was at the time. In the meantime, something new has happened.

    Timer, sure, for what ?

    Using a timer is a way to run some processing with some delay and/or at regular interval. There are two cases:

    (1) it's just to run some short code periodically without any thread concern, no trouble, no mess. If the plain Windows Forms timer is not suitable, then System.Timers.Timer with its SynchronizingObject property makes it more straightforward than System.Threading.Timer .

    (2) what you're coding is in the realm of asynchronous concurrent processing. That has traditionally been error-prone, difficult to debug, to get right, whatever the plain timer used.

    In case 2 you might get away with traditional approach, but beware, complexity is lurking and ready to eat you not just once but any time you just don't make the best choice, with cumulative effects.

    Now we've got something better

    If your situation deals with some kind of "event" handling (whatever the way it's coded: keypresses, mouse buttons, bytes from a serial port, from a network connection, from measurements, etc), you should consider Reactive Programming.

    Reactive Programming has in recent years somehow uncovered how to code for these situations, while not falling into complexity traps.

    So, technically the following link is an answer to the question: it is a timer which is in the System.Reactive.Linq namespace: Observable.Timer Method (System.Reactive.Linq)

    To be fair, it's a timer that comes and plays well with the Reactive Programming mindset and a lot of game-changing stuff. Yet it might or might not be the best tool, depending on the context.

    Since this question is .NET-centric, you might be interested in Good introduction to the .NET Reactive Framework

    Or for a clear, illustrated, more general (not Microsoft-centric) document, this seems good The introduction to Reactive Programming you've been missing.

提交回复
热议问题