How do I update a Label from within a BackgroundWorker thread?

£可爱£侵袭症+ 提交于 2019-11-29 12:40:55

This will help you.

To Execute synchronously:

Application.Current.Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))

To Execute Asynchronously:

Application.Current.Dispatcher.BeginInvoke(new Action(() => { status.Content = e.ToString(); }))

Use the capabilities already built into the BackgroundWorker. When you "report progress", it sends your data to the ProgressChanged event, which runs on the UI thread. No need to call Invoke().

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    bgWorker.ReportProgress(0, "Some message to display.");
}

private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    status.Content = e.UserState.ToString();
}

Make sure you set bgWorker.WorkerReportsProgress = true to enable reporting progress.

If you're using WPF, I'd suggest looking into DataBinding.

The "WPF way" to approach this would be to bind the label's Content property to some property of your model. That way, updating the model automatically updates the label and you don't have to worry marshalling the threads yourself.

There are many articles on WPF and databinding, this is likely as good a place to start as any: http://www.wpf-tutorial.com/data-binding/hello-bound-world/

You need to use

Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))

instead of status.Invoke(...)

You really should think about using the power of "Data Binding" in WPF.

You should be updating an object in your view model and binding that to your user interface control.

See MVVM Light. Simple and easy to use. Don't code WPF without it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!