stopwatch 依赖_其中定时器是依赖于系统时间?

I haven't tested this yet. I am hoping someone already knows the answer, so I don't have to write a test application, otherwise I will. :)

Usually when I want to compare time, I just store DateTime.Now and compare it at a later time. I believe this gives wrong results when the user changes the user's system time somewhere in between.

It made me wonder whether timers behave the same way. Which .NET timers are dependent on the set system time? Consider starting a timer which needs to elapse in one hour. Will it trigger when I set system time one hour forward?

I never really cared about this possible behavior, but it might be important in some scenarios. Which timers are safe against this scenario, and which ones most definitely aren't?

解决方案

I'll justquote Jim Mischel comments, as it's the most relevant answer to my question.

None of the timers depend on the system time. That is, the user

changing the clock will not affect System.Windows.Forms.Timer,

System.Timers.Timer, or System.Threading.Timer. Nor will it affect

Stopwatch or Environment.TickCount. Also, there's no "overhead" to

using Stopwatch. It's not like the value is continually updated. It's

lazily evaluated (i.e. Ticks is updated when it's referenced).

Documentation for Stopwatch says: "TheStopwatch measures elapsed time

by counting timer ticks in the underlying timer mechanism. If the

installed hardware and operating system support a high-resolution

performance counter, then the Stopwatch class uses that counter to

measure elapsed time." If you look up info on the high-resolution

performance counter, you'll see that it doesn't depend on the system

time

Timers are similar. System.Threading.Timer is based on Windows Timer

Queue Timers. See that documentation. System.Timers.Timer is just a

wrapper around System.Threading.Timer. System.Windows.Forms.Timer is a

wrapper around the Windows SetTimer and KillTimer functions.

Documentation for those indicates that they are not dependent on the

system time.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值