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 Elapsed property of StopWatch
is read only, which makes sense. A stopwatch simply measures the amount of time that passed between start and stop.
If you want to add a timespan to the value - get the Elapsed
value in a variable and add a timespan to it, after you have measured it (i.e. after stopping).
If you locate this file into your project -- there is nothing you need to change in your project -- this wrapper have the same name, all of same methods/parameters as original stopwatch. But with additional few:
.
using System;
public class Stopwatch : System.Diagnostics.Stopwatch
{
TimeSpan _offset = new TimeSpan();
public Stopwatch()
{
}
public Stopwatch(TimeSpan offset)
{
_offset = offset;
}
public void SetOffset(TimeSpan offsetElapsedTimeSpan)
{
_offset = offsetElapsedTimeSpan;
}
public TimeSpan Elapsed
{
get{ return base.Elapsed + _offset; }
set{ _offset = value; }
}
public long ElapsedMilliseconds
{
get { return base.ElapsedMilliseconds + _offset.Milliseconds; }
}
public long ElapsedTicks
{
get { return base.ElapsedTicks + _offset.Ticks; }
}
}
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
I think you want to start your Stopwatch
after a certain mount of time specified by a TimeSpan
. I wonder why you don't want to start your Stopwatch
at a time specified by a DateTime
instead?
public class MyStopwatch : Stopwatch
{
public void Start(long afterMiliseconds)
{
Timer t = new Timer() { Interval = 1 };
int i = 0;
t.Tick += (s, e) =>
{
if (i++ == afterMiliseconds)
{
Start();
t.Stop();
}
};
t.Start();
}
}
//use it
var offsetTimeStamp = new System.TimeSpan(0,0,0).Add(TimeSpan.FromSeconds((double)jd.ActualTime));
myStopwatch.Start((long)offsetTimeStamp.TotalMiliseconds);