Edit for better understanding…
I have a Form1.cs file and a separate Class.cs file.
In Form1 I have a bgWorker that calls Class.myFunc(), this does three foreach loops, each loop return some values such as string ClientName, or string ClientOrder.
I want to return these values from Class.myFunc to bgWorker (which is inside Form1, remember) and insert them into a ListView, Textbox, or whatever.
So the problem is: How I return string values from Class.myFunc to BgWorker?
I hope someone can help me with this…
Form1.cs
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
ControlsHelper.ControlInvike(listProcess, () => listProcess.Items.Add("Current").Name = "item1");
myOtherClass cp = new myOtherClass();
cp.myFunc();
}
Class.cs
public void myFunc()
{
foreach (string Client in Clients)
{
// Do something
// Return Client and insert into listview, richtextbox, W/E
}
}
To expand on Daniel Hilgarth’s answer: if the BGW doesn’t exist in the context of
Class.cscan you not pass it in as a parameter so that you can update your progress. In your DoWork signature theobject senderis the BGW you want to cast as BackgroundWorker to send intomyFunc.So you’d have
An even better than using a generic
List<string>you could make your own class which has all the items you need then you can call them explicitly instead of referring to a list index.Then in your ProgressChanged event handler
To ensure thread safety I use this extension method for controls. It’s really great having this logic wrapped up in an extension method. You don’t need to think about the Invoke structure whenever you need to call it, you just call it.
And be sure to tie it all together when you instantiate your BackgroundWorker using