Jamie Keeling Jamie Keeling - 1 year ago 64
C# Question

Accessing UI Control from BackgroundWorker Thread

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

alt text

which calls this:

alt text

(Apologies, code formatting won't work)

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

alt text

How would I get around this?


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;


rmx rmx
Answer Source

Here's a snippet which I find very handy:

public static void ThreadSafe(Action action)
        new MethodInvoker(action));

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

ThreadSafe(() =>
    [your code here]


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download