我在VB.NET程序中有一个时钟功能,显示时间,包括秒。我现在有一个计时器不断使用现在轮询。我必须经常轮询系统时钟,因为我需要让第二次更新与系统时钟同步。

只有在秒数发生变化时才能更直接地访问时间吗?

是否有更有效的方法来编写此代码?

如果您需要更多信息,请与我们联系。

有帮助吗?

解决方案

为什么不使用计时器组件?这假设您使用的是GUI而不是构建服务。

您可以调用执行轮询的同步例程,使计时器非常接近更改的秒数,然后委托给计时器。您可以每分钟调用一次同步例程,以确保您没有任何操作系统漂移。

话虽如此,我确信有一种方法可以检测秒变化事件,我只是不知道该怎么做。

更新

此链接的实施与我想象的类似。只需修改它,这样你就不会永久陷入循环中瞧!你有同步例程。

更新2:

根据Shog9的反馈,我认为这可能比投票更好:

Public Class Form1
   Private WithEvents clockTimer As New Timer
   Private currentTime As DateTime = DateTime.MinValue

   Private Sub ClockTick(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles clockTimer.Tick

      UpdateTimer()
      DisplayTimer()
   End Sub

   Private Sub UpdateTimer()
      currentTime = DateTime.Now

      clockTimer.Stop()
      clockTimer.Interval = 1000 - currentTime.Millisecond
      clockTimer.Start()
   End Sub

   Private Sub DisplayTimer()
      lblTime.Text = currentTime.ToString("T")
   End Sub

   Private Sub Form1_Load(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load

      UpdateTimer()
      DisplayTimer()
   End Sub
End Class

现在,基于我的初步测试,每个Tick事件都有一些偏差。在我的机器上,它在12到20毫秒之间变化。如果有人知道如何可靠地纠正漂移,我会对学习感兴趣。

其他提示

使用Timer对象,将其设置为“interval”。为0,设置为“已启用”为真。这将大约每15毫秒触发一次(基于您的硬件配置)。在该方法中,设置MyLabel.Text = DateTime.Now.ToString()(或者你正在做的任何事情)。

这非常有效。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top