我想制作一个同时显示UTC和Local的时钟。 所以,我使用System.Threading中的Timer类,如下所示:
private static object _lockObj = new object();
static bool isDisplaying = false;
public MainWindow()
{
InitializeComponent();
System.Threading.Timer _timer = _timer = new System.Threading.Timer(timer_expired, null, 0, 1000);
}
private void timer_expired(object state)
{
if(!isDisplaying)
lock (_lockObj)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.UTC_TIME.Text = DateTime.UtcNow.ToString("MMM-dd HH:mm:ss");
this.LOCAL_TIME.Text = DateTime.Now.ToString("MMM-dd HH:mm:ss");
}));
isDisplaying = false;
}
}
但几分钟后大约15分钟左右,时钟停止了。 在调试模式下,我可以看到:
The thread 0x1e10 has exited with code 259 (0x103).
如何让这个时钟一直运行?