UI not working after DispatcherTimer

534 views Asked by At

After implementing DispatcherTimer, my application that involves user interaction do not work. For more information, I am trying to develop an application using leap motion. Need the timer work together with the UI for user to make some gestures and stop after timer ends, but now the leap motion no longer detect any gesture after using dispatcher timer. Some advice please thanks!

My code for timer:

public MainWindow()
{
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    dispatcherTimer.Tick += dispatcherTimer_Tick;
    dispatcherTimer.Start();
}

void dispatcherTimer_Tick(object sender, EventArgs e)
{
    if (time > 0)
    {
        if (time <= 10)
        {
            if (time % 2 == 0)
            {
                TBCountdown.Foreground = Brushes.Red;
            }
            else
            {
                TBCountdown.Foreground = Brushes.Red;
            }
            time--;
            TBCountdown.Text = string.Format("00:0{0}:0{1}", time / 60, time % 60);
        }
        else
        {
            time--;
            TBCountdown.Text = string.Format("00:0{0}:{1}", time / 60, time % 60);
        }
    }
    else
    {
        dispatcherTimer.Stop();
        MessageBox.Show("Completed");
    }
}
2

There are 2 answers

1
AjS On

I beleive the Dispatacher is running on the same UI thread aand hecne making UI unresponsive. A better way is to use BackgroundWorker to do time consuming tasks on background thread.

0
user3098072 On

Thanks for all the suggestions. Dan Puzey was right, it is designed to work with WPF UI in a responsive way. It only lags a lil sometimes, but overall it should still respond. Hopefully it doesn't hangs anymore. Thanks!