简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM