从 BackgroundWorker 线程访问 UI 控件 [英] Accessing UI Control from BackgroundWorker Thread

查看:36
本文介绍了从 BackgroundWorker 线程访问 UI 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Windows 窗体上有一个按钮调用 RunWorkerAsync() 方法,这反过来执行一个操作,然后更新同一窗体上的 ListBox.

I have a button on my windows form that calls the RunWorkerAsync() method, this in turn performs an action which then updates a ListBox on the same form.

在 DoWork 事件完成后,我为事件分配结果(这是一个列表),我处理 RunWorkerCompleted() 事件,然后执行以下代码来更新我的列表框

After the DoWork event has finished I assign the Result for the event (Which is a list), I process the RunWorkerCompleted() event and then perform the following code to update my Listbox

调用这个:

(抱歉,代码格式不起作用)

(Apologies, code formatting won't work)

现在,当我运行应用程序并按下刷新按钮时,出现以下异常:

Now when I run the application and press the refresh button the following exception appears:

我该如何解决这个问题?

How would I get around this?

在以下语句中抛出异常,这发生在 DoWork 方法中,我清除内容以保持列表最新;

The exception is thrown on the folowing statement, this occurs in the DoWork method where I clear the contents to keep the list up to date;

listBoxServers.Items.Clear();

推荐答案

这是我觉得非常方便的一个片段:

Here's a snippet which I find very handy:

public static void ThreadSafe(Action action)
{
    Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, 
        new MethodInvoker(action));
}

您可以将任何 Action 类型的委托或简单的 lambda 传递给它,如下所示:

You can pass it any delegate of Action type or simply a lambda like this:

ThreadSafe(() =>
{
    [your code here]
});

ThreadSafe(listBoxServers.Items.Clear);

这篇关于从 BackgroundWorker 线程访问 UI 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆