问题
If I have a shared System.Diagnostics.Stopwatch
instance, can multiple threads call shared.ElapsedTicks
in a safe manner and get accurate results?
Is there any difference in terms of thread-safety/accuracy between using a shared instance of Stopwatch in this way, and using the static GetTimeStamp()
method?
I'm measuring intervals of around 180ms, and finding that using the shared instance is giving me a larger spread of results, including a significant number that are shorter than I would expect.
The machine has multiple CPUs (2 * Intel X5550 for what it's worth)
回答1:
From MSDN: "Any instance members are not guaranteed to be thread safe."
回答2:
You can use https://msdn.microsoft.com/en-us/library/dd642243(v=vs.110).aspx
ThreadLocal<T>
like this:
ThreadLocal<Random> _localRandom = new ThreadLocal<Random>(() => new Random());
ThreadLocal<Stopwatch> _localStopwatch = new ThreadLocal<Stopwatch>(() => new Stopwatch());
public void SomeTest()
{
Action someAction = () =>
{
_localStopwatch.Value.Reset();
_localStopwatch.Value.Start();
Thread.Sleep(_localRandom.Value.Next(100, 500));
_localStopwatch.Value.Stop();
Debug.Print(_localStopwatch.Value.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture));
};
var actions = Enumerable.Range(0, 1000).Select(i => someAction).ToArray();
Parallel.Invoke(new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount}, actions);
}
回答3:
Looking at the source code, it is not thread-safe.
回答4:
Looking at the source code, it is thread-safe, but you must not use: Stop()
, Reset()
and Restart()
.
So, if you start a shared instance, does not modify it and call only ElapsedXXX
properties, you should be fine.
回答5:
To add to the other answers here, while this property is theadsafe as long as you do not call the Start()
, Reset()
, or Stop()
methods, it is important to note that if you are using the ticks for arithmetic and then passing the value into a TimeSpan
constructor, for example, one stopWatch.ElapsedTicks
Tick is not equivalent to TimeSpan
Ticks as described here. To get equivalent ticks you would want to use stopWatch.Elapsed.Ticks
.
Would have left this as a comment on another answer but i do not have enough reputation :/
来源:https://stackoverflow.com/questions/6664538/is-stopwatch-elapsedticks-threadsafe