Is Environment.TickCount affected by system time adjustments?

妖精的绣舞 提交于 2019-12-12 15:51:31

问题


I'm curious as to how the .NET BCL property Environment.TickCount is implemented. In particular I'd like to now if it is affected by system time adjustments.

My first guess as to how the property was implemented was that it was simply a managed wrapper around the GetTickCount method. However, the documentation for the GetTickCount method states that it is affected by adjustments made by the GetSystemTimeAdjustment function but the documentation for Environment.TickCount does not mention anything about time adjustments.

I'm trying to figure out if the Environment.TickCount can be used as a (albeit low-precision) consistently increasing time value.


回答1:


No, Environment.TickCount is not affected by adjustments of the system time. That was my interpretation of the documentation, but my curiosity demanded harder proof, so I had the following code run while adjusting the system back and forth one hour:

while (true)
{
    Console.WriteLine(Environment.TickCount);
    Thread.Sleep(1000); 
}

...and the output showed a perfect sequence that was not affected by the time adjustments.

Update
So I did some more homework, triggered by Marcus' question in the comments below. I am quite sure (could not confirm though) that Environment.TickCount makes a call to GetTickCount that has the following mentioned in the docs:

The resolution of the GetTickCount function is limited to the resolution of the system timer, which is typically in the range of 10 milliseconds to 16 milliseconds. The resolution of the GetTickCount function is also affected by adjustments made by the GetSystemTimeAdjustment function.

So, while it is not affected by altering the system time, it seems that will be affected by adjustments that are caused by a call to SetSystemTimeAdjustment.




回答2:


No, it's not affected by system time adjustments.

Whether it's suitable for a "consistently increasing time value" depends on your exact requirements. From the MSDN documentation:

The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.



来源:https://stackoverflow.com/questions/1858989/is-environment-tickcount-affected-by-system-time-adjustments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!