【发布时间】:2022-03-02 19:23:02
【问题描述】:
我使用 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 毫秒 54 和 950 毫秒 ..... 毫秒等等,因为我只显示时间直到几秒钟,所以它给人一种我落后一秒的错觉。
什么是显示时间的推荐方式与任务栏显示的时间相匹配,可以将计时器间隔设置为每 500 毫秒滴答一次?
【问题讨论】:
-
只需使用更短的间隔,甚至可能是 200 毫秒。额外的工作量可以忽略不计。您还可以将当前秒保留在字段中,并在调用 DateTime.Now 后将其与新值进行比较。只有当它发生变化时,才进行转换和标签更新。