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

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

问题描述

我在Windows窗体上有一个按钮,该按钮调用RunWorkerAsync()方法,该按钮依次执行一个操作,然后更新同一窗体上的ListBox.

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

这叫做

(抱歉,代码格式无效)

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

我该如何解决?

在以下语句上引发了异常,这发生在DoWork方法中,在该方法中,我清除了内容以使列表保持最新状态; <​​/p>

listBoxServers.Items.Clear();

解决方案

这是一个非常方便的代码段:

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

您可以向其传递任何Action类型的委托,也可以仅将其传递给lambda:

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

ThreadSafe(listBoxServers.Items.Clear);

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.

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

which calls this:

(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?

Edit:

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

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

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

or

ThreadSafe(listBoxServers.Items.Clear);

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

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