0

I want to make a clock which display UTC and Local together. So, I used Timer class from System.Threading like below:

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;
    }
}

But a few minutes later like 15 minutes or so, the clock stops. In a debug mode, I can see:

The thread 0x1e10 has exited with code 259 (0x103).

How can I run this clock works all the time?

Daebarkee
  • 633
  • 2
  • 6
  • 18
  • A local variable isn't enough to prevent the timer object from getting garbage collected. Make it a field of your class instead. Or use System.Timers.Timer, it doesn't have this problem. It has other ones however, fix the variable. – Hans Passant May 22 '14 at 20:18
  • @HansPassant. Do you mean System.Threading.Timer object can be garbage collected anytime? I have used Threading.Timer several times in many windows service applications for periodic batch job. Your comment means that all my services are unstable. :( – Daebarkee May 22 '14 at 22:00

0 Answers0