how to execute certain class method no more than once per 100ms?

后端 未结 4 441
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 05:51

I\'m writing trading software and need to QoS one method that should not be executed more often than 10 times per second. As I\'m begginer in C# and almost not familar with

4条回答
  •  不要未来只要你来
    2021-01-15 06:28

    Your technique of using Stopwatch is the best solution to prevent the code from executing more frequently. As others have said, using a Timer is a better solution if you want to make sure that the method is executed on a schedule.

    Any approach based on DateTime is fundamentally broken because it will fail when the date changes. This is especially noticeable during the Daylight Saving Time switches. When we "spring ahead", there's the potential of the update running twice in quick succession because the code thinks that it's been an hour since the previous update. That's not too bad. But when we "fall back", the update will be suspended for a full hour because the last update time is set an hour ahead.

    The same kind of thing can happen, although not as severely, if your computer is set to update its time periodically from an NTP server. If the time is set ahead, then there is the potential for two updates to happen in quick succession. If the time is set back, there's the potential for updates not to happen for the amount of time the clock was set back.

    There are ways around the problem (such as using the absolute value of the number of milliseconds), but then you're just putting a bandage on a broken solution. You shouldn't depend on DateTime for intervals like this because your program isn't in control of the system clock--it can change at any time.

    Stopwatch is the only reasonable solution here because it depends on the CPU's performance counter, which only increases. You don't have the problems of somebody setting the counter back, and you don't have the rollover problems you would encounter with something like Environment.TickCount.

    There's some idea that Stopwatch incurs a performance penalty that DateTime doesn't. My testing shows that to be untrue.

提交回复
热议问题