If I have a shared System.Diagnostics.Stopwatch
instance, can multiple threads call shared.ElapsedTicks
in a safe manner and get accurate results?<
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.
From MSDN:
Any instance members are not guaranteed to be thread safe.
Looking at the source code, it is not thread-safe.
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);
}