Why using Dispatcher.CurrentDispatcher.BeginInvoke does not update my GUI but using BeginInvoke does?

Viewed 707

I am confused about the differences between Dispatcher.CurrentDispatcher.BeginInvoke and BeginInvoke

I have the following portion of code that didn't work, the code in UpdateCounts method is being ignored:

private void Start()
{
    _testResults = new TestResults(ModelNameTextBox.Text);
    _timer = new System.Threading.Timer(UpdateCounts, null, 0, 500);            
}

private void UpdateCounts(object info)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
    {
        PassCountLabel.Text = _testResults.PassedCount.ToString();
        RequestCountLabel.Text = _testResults.RequestedCount.ToString();                
    }));
}

But once removing Dispatcher.CurrentDispatcher, it works fine:

private void UpdateCounts(object info)
{
    BeginInvoke(new Action(() =>
    {
        PassCountLabel.Text = _testResults.PassedCount.ToString();
        RequestCountLabel.Text = _testResults.RequestedCount.ToString();                
    }));
}
1 Answers

The Dispatcher.CurrentDispatcher.BeginInvoke will work only if you call it from the UI thread,if not it calls the current thread.

You have to use Application.Current.Dispatcher to call the UI thread.

Related