How to directly access the UI thread from the BackgroundWorker thread in WPF?

只谈情不闲聊 提交于 2019-12-01 11:01:27

Have you looked at using Dispatcher.Invoke?

Dispatcher.Invoke(new Action(() => { Button_Start.Content = i.ToString(); }));

Or use BeginInvoke if you want something to happen asynchronously.

Your best option is to continue using .ReportProgress and .ProgressChanged. Is there a particular reason this isn't sufficient?

There's no way you can directly access the UI from another thread. The only solution is to raise an event in the thread and then catch it in the UI thread.

If you don't want to use a BackgroundWorker thread you'll need something like this to raise the event in the thread:

        // Final update
        if (Library_Finished != null)
        {
            Library_Finished(this, null);
        }

which is declared like this:

    public event EventHandler Library_Finished;

Then you'll need something like this in the UI thread to catch and process the event:

    private void Library_Finished(object sender, EventArgs e)
    {
        Action action = () => FinalUpdate();
        if (Thread.CurrentThread != Dispatcher.Thread)
        {
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, action);
        }
        else
        {
            action();
        }
    }

But even if you use a BackgroundWorker you'll still need to implement the thread checking code before accessing the UI elements.

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