Wade Pedersen
Wade Pedersen

Reputation: 38

TimeSpan and DispatchTimer

I'm using a class to modify a DateTime and using a TimeSpan to display X hours, Y minutes, Z seconds to a WPF label every second with a DispatchTimer. The code itself gives the proper timespan, however the DispatchTimer is giving the wrong output. Can I get some input on what is going on here?

The ModifiedTime Minutes properties is still being queried during debug breaks (hovering over ModifiedTime.Minutes keeps giving an increasing number.), is this the norm?

Runtime output starts at 3 minutes, then displays 8 minutes, 13, 18, 23, 28, etc.

Library:

public Clock() {
  load_ = DateTime.Now;
  time_ = new DateTime();
  time_ = DateTime.Now;
  modifiedTime_ = new DateTime();         
  modifiedTime_ = DateTime.Now;
  difference = TimeSpan.Zero;
}

public TimeSpan ModifiedTime {
  //Convert the real time to timespan.
  //display X Years, Y Days, Z Hours...
  get {
  modifiedTime_ = modifiedTime_.AddMinutes(1.0);
  difference = modifiedTime_.Subtract(time_);
  return difference;
  }
  set { difference = value; }
}

WPF:

DispatcherTimer dispatcherTimer; 
public MainWindow() {
  InitializeComponent();
  dispatcherTimer = new DispatcherTimer();
  dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
  dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
  dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e) {
  lblModTime.Content = clock.ModifiedTime.Hours + " hours, " + clock.ModifiedTime.Minutes + " minutes, " + clock.ModifiedTime.Seconds + " seconds, " + clock.ModifiedTime.Milliseconds + " milliseconds.";
}

Upvotes: 0

Views: 532

Answers (2)

Michael Jensen
Michael Jensen

Reputation: 26

Right, every time you call clock.ModifiedTime. in your dispatcher (4 times!) you add a minute to the modified time, plus possibly once more for evaluating the statement in the debugger. That would explain your incrementing your display by 5 each time.

Upvotes: 1

Despertar
Despertar

Reputation: 22372

If I understand correctly, you want to add one minute to the time started for every second that passed. So take the difference in seconds, then add that as minutes to time started for your new time.

public TimeSpan ModifiedTime
{
    get
    {
        TimeSpan elapsed = DateTime.Now - TimeStarted;
        return TimeStarted.AddMinutes(elapsed.TotalSeconds);
    }
}

Upvotes: 1

Related Questions