Is Stopwatch.ElapsedTicks threadsafe?

前端 未结 4 570
野的像风
野的像风 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 17:03

    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);
        }
    

提交回复
热议问题