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