从开始指定时间秒表 [英] Start a stopwatch from specified time

查看:210
本文介绍了从开始指定时间秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着开始从给定的时间秒表(十进制值从数据库中抽取)。但是,由于Stopwatch.Elapsed.Add返回一个新的时间跨度,而不是修改秒表,我不能工作了前进的最好方式。

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 the stopwatch, I can't work out the best way forward.

var offsetTimeStamp = new System.TimeSpan(0,0,0).Add(TimeSpan.FromSeconds((double)jd.ActualTime));
Stopwatch.Elapsed.Add(offsetTimeStamp);
Stopwatch.Start();



任何想法,我该怎么办呢?干杯

Any ideas how I can do this? Cheers

推荐答案

正常秒表不支持初始化具有偏移时间跨度和时间跨度结构,所以消逝是不可改变的。你可以写一个秒表的包装:

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

现在,你可以添加一个启动-timespan:

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

这篇关于从开始指定时间秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆