If I have a shared System.Diagnostics.Stopwatch
instance, can multiple threads call shared.ElapsedTicks
in a safe manner and get accurate results?<
You can use https://msdn.microsoft.com/en-us/library/dd642243(v=vs.110).aspx
ThreadLocal
like this:
ThreadLocal _localRandom = new ThreadLocal(() => new Random());
ThreadLocal _localStopwatch = new ThreadLocal(() => 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);
}