Is Stopwatch.ElapsedTicks threadsafe?

前端 未结 4 571
野的像风
野的像风 2020-12-20 16:03

If I have a shared System.Diagnostics.Stopwatch instance, can multiple threads call shared.ElapsedTicks in a safe manner and get accurate results?<

相关标签:
4条回答
  • 2020-12-20 16:49

    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.

    0 讨论(0)
  • 2020-12-20 16:57

    From MSDN:

    Any instance members are not guaranteed to be thread safe.

    0 讨论(0)
  • 2020-12-20 16:57

    Looking at the source code, it is not thread-safe.

    0 讨论(0)
  • 2020-12-20 17:03

    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);
        }
    
    0 讨论(0)
提交回复
热议问题