views:

37

answers:

2

I have a background worker that runs and looks for stuff, and when it finds stuff, I want to update my main WinForm. The issue that I'm having is that when I try to update my WinForm from my background worker, I get errors that tell me I can't modify things that were made outside of my background worker (in other words, everything in my form).

Can someone provide a simple code example of how I can get my code to work the way I want it to? Thanks!

+5  A: 

I believe you're looking for the OnProgressChanged Event. More info with example here: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.onprogresschanged.aspx

Donn Felker
+4  A: 

If I understand correctly, you want to make a change on the form itself, however you cannot change a control on a form from a thread other than the thread the form was created on. To get around this I use the Form.Invoke() method like so:

public void DoSomething(string myArg) 
{
    if(InvokeRequired) 
    {
        Invoke(new Action<string>(DoSomething), myArg);
    }
    else
    {
        // Do something here
    }
}

The InvokeRequired property checks the calling thread to determine if it is the proper thread to make changes to the form, if no the Invoke method moves the call onto the form's window thread.

Coding Gorilla
Ok, so I stick this code in my main form, Then how do I trigger this in my background worker?
Soo
You put the thing you want to do in the 'do something here' spot. Then you call DoSomething from the worker thread as if it were magic! Well it's not ... The first call invoke is required, so it runs the invoke. This blocks the worker thread and tells the main thread (gui thread) to basically call that same function on its own. It does, only this time, no invoke required; the else runs. You can run IFs and Splits on myArg to do all kinds of things with one sub. On return the worker thread resumes.
FastAl
So if you wanted to say, change the text property of a text box you could pass that text in myArg and replace the '// Do something here' with: myTextBox.Text = myArg;You can also add additional parameters to the method as needed using different variations of the Action<> delegate.
Coding Gorilla
FastAI, Thanks much! You have made me a very happy man. My code is working just as it should. Thanks also to Coding Gorilla of course for the code snippet. Have a killer weekend both of you! :D
Soo