我正在使用DispatcherTimer使用(基本上在标签Datetime.Now格式为hh:mm:ss tt中)显示应用程序中的时间。
_timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 1)};
_timer.Tick += _timer_Tick;
_timer.Start();
private void _timer_Tick(object sender, EventArgs e)
{
try
{
var now = DateTime.UtcNow;
var nowUserSelected =
TimeZoneInfo.ConvertTimeFromUtc(now,
(DataContext as MainViewModel)?.UserSelectedTimeZone ?? TimeZoneInfo.Local);
ClockCurrent.Text = $"{nowUserSelected:hh:mm:ss tt}";
}
catch (Exception exp)
{
Log.Error("Error occurred while reporting time", exp);
}
}
问题是,如果用户从任务栏中打开时钟(如果您单击任务栏中的时间,则会弹出一个窗口,显示当前时间,包括秒),有时我的应用中的时间似乎是关闭一秒钟(有时!)。我认为可能会发生这种情况,因为必须将计时器设置为从当前时间开始每秒滴答一次,这可能是 10:50:53 PM和950 ms ,并且可以说一下,然后滴答每一秒54和950 ms ..... ms等等,由于我只显示几秒钟的时间,所以给人以错觉,我落后了一秒钟。
显示与任务栏显示的时间相匹配的时间的建议方法是什么,也许将计时器间隔设置为每500 ms计时一次?
答案 0 :(得分:-1)
启动时检查ms。一秒钟后立即刷新,然后每秒刷新一次
更好:在UI更新结束时,您确定何时必须进行下一次UI更新。