c# - Start a stopwatch from specified time -
im trying start stopwatch given time (decimal value pulled database). however, because stopwatch.elapsed.add returns new timespan rather modify stopwatch, can't work out 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 can this? cheers
the normal stopwatch
not support initialization offset timespan , timespan
struct
, therefore elapsed
immutable. write 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 { { return _stopwatch.elapsed + _offsettimespan; } set { _offsettimespan = value; } } }
now can add 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