I've been trying to figure out how to get my textbox's text or other property from within a background worker. Does anybody know how to do this? I cannot pass it as a param because it needs to be real-time. Thanks for the help!
Asked
Active
Viewed 1.5k times
5
-
1Why doesn't your current code work? Do you get exceptions? If yes, what kind? – svick Jul 05 '11 at 15:20
-
What do you mean by "from within a background"? – Adriano Carneiro Jul 05 '11 at 15:21
-
@Adrian apologies, I meant 'from within a background worker'. @svick in my current code I pass the text but by the time it gets to the part of the code were it uses the text, the text is old. So I need to get the text at the exact moment it is used from within the background worker. Hopefully this makes sense. – user556396 Jul 05 '11 at 15:31
-
http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t/142069#142069 – Bolu Jul 05 '11 at 15:39
4 Answers
9
I think you need to just invoke the property (pseudo-code):
private void bgw1_DoWork(object sender, DoWorkEventArgs e)
{
// looping through stuff
{
this.Invoke(new MethodInvoker(delegate { Text = textBox1.Text; }));
}
}

LarsTech
- 80,625
- 14
- 153
- 225
-
-
5I'm suppressed you didn't mention the exception *Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.* in your question.. – Bolu Jul 05 '11 at 15:48
2
Or if needed in WPF:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string text = null;
myTextBox.Dispatcher.Invoke(new Action(delegate()
{
text = myTextBox.Text;
}));
}

DeMama
- 1,134
- 3
- 13
- 32
2
Use the ReportProgress method and event of the Background worker. That will switch to the correct thread for you.

Emond
- 50,210
- 11
- 84
- 115
1
i think you should use invoke method.
here's my example.
delegate void myDelegate(string name);
//...
private void writeToTextbox(string fCounter)
{
if (this.InvokeRequired)
{
myDelegate textWriter = new myDelegate(displayFNums);
this.Invoke(textWriter, new object[] { fCounter });
}
else
{
textbox1.Text = "Processing file: " + fileCounter + "of" + 100;
}
}
//...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//...
writeToTextbox(fileCounter.ToString());
}
in dowork i manipulate some textfile and i inform the user about how many files i have processed so far.