Reputation: 13
I have this piece of code:
public void StartTimer(string roomName)
{
var roomTimer = GetRoomTimer(roomName);
var room = GetRoom(roomName);
if (roomTimer == null)
{
//Create a timer with a two second interval.
roomTimer = new System.Timers.Timer(2000);
roomTimer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, room.Item2);
roomTimer.AutoReset = true;
roomTimer.Enabled = true;
_rooms[roomName].Timer = roomTimer;
}
else
{
roomTimer.Start();
roomTimer.AutoReset = true;
roomTimer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, room.Item2);
_rooms[roomName].Timer = roomTimer;
}
}
public void StopTimer(string roomName)
{
var roomTimer = GetRoomTimer(roomName);
roomTimer.Stop();
}
private static void MyElapsedMethod(Object source, ElapsedEventArgs e, TwilioRoomDto room)
{
room.Time += room.Timer.Interval;
}
When timer is started and then when it is stopped and restarted again it does not track time nearly as accurate. It misses by almost double. Why is this the case I am holding time passes in dictionary.
Upvotes: 0
Views: 363
Reputation: 36341
That is just not the correct way to track the amount of time that has passed. If you want accurate time measurement use a stopwatch
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
A stopwatch will, depending on platform, be accurate down to sub microsecond.
If that is for some reason not what you want, a better design would be to save the start-time using DateTime.Now, and calculate the difference in time. If you want to stop and restart you can store this difference in a separate TimeSpan each time the timer is stopped. But using DateTime.Now
will have worse resolution, about 1-16ms depending on platform.
Upvotes: 1