Start a stopwatch from specified time

前端 未结 4 1781
一向
一向 2021-01-18 21:04

Im trying to start a stopwatch from a given time (decimal value pulled from a database). However, because the Stopwatch.Elapsed.Add returns a new timespan rather than modify

4条回答
  •  长情又很酷
    2021-01-18 21:28

    The normal StopWatch does not support initialization with an offset timespan and TimeSpan is a struct, therefore Elapsed is immutable. You could write a wrapper around StopWatch:

    public class StopWatchWithOffset
    {
        private Stopwatch _stopwatch = null;
        TimeSpan _offsetTimeSpan;
    
        public StopWatchWithOffset(TimeSpan offsetElapsedTimeSpan)
        {
            _offsetTimeSpan = offsetElapsedTimeSpan;
            _stopwatch = new Stopwatch();
        }
    
        public void Start()
        {
            _stopwatch.Start();
        }
    
        public void Stop()
        {
            _stopwatch.Stop();
        }
    
        public TimeSpan ElapsedTimeSpan
        {
            get
            {
                return _stopwatch.Elapsed + _offsetTimeSpan;
            }
            set
            {
                _offsetTimeSpan = value;
            }
        }
    }
    

    Now you can add a start-timespan:

    var offsetTimeStamp = TimeSpan.FromHours(1);
    var watch = new StopWatchWithOffset(offsetTimeStamp);
    watch.Start();
    System.Threading.Thread.Sleep(300); 
    Console.WriteLine(watch.ElapsedTimeSpan);// 01:00:00.2995983
    

提交回复
热议问题