Reputation: 23187
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!
Upvotes: 1
Views: 187
Reputation: 19842
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.
Upvotes: 4
Reputation: 9651
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
Upvotes: 5