我已经实现了一个带有数据绑定(bind)的 DispatcherTimer,它可以像秒表或计数计时器一样显示音频通话期间耗时。 (正如您在手机中看到的那样)
以下代码每分钟变慢“1 秒”,这不利于计算账单。你能告诉我哪里错了吗?
System.Windows.Threading.DispatcherTimer dispatcherTimer;
int seconds = 0;
public string Counter { get; set; }
public Timer()
{
InitializeComponent();
this.DataContext = this;
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
Counter = (seconds / 3600).ToString() + ":" + (seconds / 60).ToString("00") + ":" + (seconds % 60).ToString("00");
NotifyPropertyChanged("Counter");
seconds++;
}
我将这个计时器与互联网和移动设备上的其他秒表进行了比较,这个计时器每分钟延迟一秒。
最佳答案
您依赖于计时器,它似乎始终不准确,数量相同。
你为什么不采取一个时间点并存储它,
private DateTime startTime;
public Timer()
{
InitializeComponent();
startTime = DateTime.Now;
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
Counter = (DateTime.Now - startTime).ToString();
...
}
实际采用这样的代码可以说明您遇到问题的原因。那里的 ToString 方法更准确地显示计数器,包括毫秒,事实证明计时器不是每 1 秒触发一次,而是更像是每 1.01 秒触发一次。
我得到这样的值,
1.008
1.02
1.031
1.03901
等等
然后你可以用这个替换上面的,
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
TimeSpan elapsedTime = (DateTime.Now - startTime);
Counter = string.Format("{0:hh\\:mm\\:ss}", elapsedTime);
它的格式将与您之前的格式一样,没有毫秒。
关于c# - DispatcherTimer 在更新 UI 时每分钟变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8569814/