Will reading Stopwatch.ElapsedMilliseconds from a different thread give the correct value?

StackOverflow https://stackoverflow.com/questions/19205784

  •  30-06-2022
  •  | 
  •  

Question

I have started an instance of Stopwatch and would like to read it's ElapsedMilliseconds from another thread:

var diff = myStopwatch.ElapsedMilliseconds - someOtherValue;

However I have read the compiler optimises code assuming it is running on the same thread which could result in the above line reading a value from registry rather then getting the actual value at the precise point in time it is executed. Will this affect me? If so how do I work around it?

Était-ce utile?

La solution

Stopwatch pinvokes the QueryPerformanceCounter() winapi function, optimization does not affect that in any way. The winapi function depends on the HAL, the Hardware Abstraction Layer to provide the counter source. Most typically a counter available in the chipset. Different machines use different chipsets, the reason that Stopwatch.Frequency property is exposed. And accordingly different HAL implementations so there can be no hard guarantee that your motherboard doesn't have cooties. Microsoft covers that liability with this note in the MSDN article:

On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function.

These kind of bugs were not entirely uncommon 20 years ago, unheard of today.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top