0

我正在使用一个类来修改 DateTime 并使用 TimeSpan 通过 DispatchTimer 每秒向 WPF 标签显示 X 小时、Y 分钟、Z 秒。代码本身给出了正确的时间跨度,但是 DispatchTimer 给出了错误的输出。我能得到一些关于这里发生的事情的意见吗?

在调试中断期间仍在查询 ModifiedTime Minutes 属性(悬停在 ModifiedTime.Minutes 上不断给出越来越多的数字。),这是常态吗?

运行时输出从 3 分钟开始,然后显示 8 分钟、13、18、23、28 等。

图书馆:

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.";
}
4

2 回答 2

1

如果我理解正确,您想在每经过一秒的开始时间上增加一分钟。因此,以秒为单位计算差异,然后将其添加为新时间开始的分钟数。

public TimeSpan ModifiedTime
{
    get
    {
        TimeSpan elapsed = DateTime.Now - TimeStarted;
        return TimeStarted.AddMinutes(elapsed.TotalSeconds);
    }
}
于 2013-01-23T04:05:01.290 回答
1

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.

于 2013-01-23T04:06:00.213 回答