我正在使用Visual Studio 2022开发一个名为Charms Bar Port的新GitHub存储库,该存储库要求UI在左下角显示时钟和日期,如下图所示。
然而,时钟似乎永远不会更新,不管是否存在:
<<ul>背景工人/gh><<li>计时器/gh>是否有一种好方法可以在循环中持续跟踪时间?
使用来自外部源的后台工作器和/或计时器的一些代码从未起作用。例如:8:34;即使时间是"9:00",也会卡在屏幕上。
Timer t = new Timer();
private void Form1_Load(object sender, EventArgs e)
{
// Normally, the timer is declared at the class level, so that it stays in scope as long as it
// is needed. If the timer is declared in a long-running method, KeepAlive must be used to prevent
// the JIT compiler from allowing aggressive garbage collection to occur before the method ends.
// You can experiment with this by commenting out the class-level declaration and uncommenting
// the declaration below; then uncomment the GC.KeepAlive(aTimer) at the end of the method.
//System.Timers.Timer aTimer;
// Create a timer and set a two second interval.
t = new System.Timers.Timer();
t.Interval = 2000;
// Create a timer with a two second interval.
//t = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
t.Elapsed += OnTimedEvent;
// Have the timer fire repeated events (true is the default)
t.AutoReset = true;
// Start the timer
t.Enabled = true;
// If the timer is declared in a long-running method, use KeepAlive to prevent garbage collection
// from occurring before the method ends.
GC.KeepAlive(t);
}
//timer eventhandler
private void OnTimedEvent(object sender, EventArgs e)
{
//update label
Date.Content = DateTime.Today.ToString("MMMM d");
Week.Content = DateTime.Today.ToString("dddd");
Clocks.Content = DateTime.Now.ToString("hh:mm");
t.Enabled = true;
}
}
你应该使用分派器从不同的线程更新UI。
你的代码应该是:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
_initTimer();
}
private Timer t = null;
private readonly Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
private void _initTimer()
{
t = new System.Timers.Timer();
t.Interval = 1000;
t.Elapsed += OnTimedEvent;
t.AutoReset = true;
t.Enabled = true;
t.Start();
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
dispatcher.BeginInvoke((Action)(() =>
{
DateTime today = DateTime.Now;
Clocks.Content = today.ToString("hh:mm:ss");
// do additional things with captured 'today' variable.
}));
}
}