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

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

问题描述

我有我的Windows窗体上按钮调用的RunWorkerAsync()方法,这反过来执行一个动作,然后更新同一窗体上的列表框。

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()事件,然后执行以下code更新我的列表框

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

调用该:

(道歉,code格式无效)

(Apologies, code formatting won't work)

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

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

您可以通过它行动任何代表键入或只是一个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控件 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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