In my windows forms application, I have a textbox component and backgroundworker . In the dowork backgroundworker event, I'm trying to access the value of a text field. How can i do this? I get the following exception in the dowork event handler code when I try to access the value of a text field:
textbox
backgroundworker
dowork
Cross-thread operation not valid: Control 'txtFolderName' accessed from a thread other than the thread it was created on`
You can only access textbox / form controls in the GUI thread, you can do it like this.
textbox / form controls
if(txtFolderName.InvokeRequired) { txtFolderName.Invoke(new MethodInvoker(delegate { name = txtFolderName.text; })); }
You need to use MethodInvoker . How:
BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate(object sender, DoWorkEventArgs e) { MethodInvoker mi = delegate { txtFolderName.Text = "New Text"; }; if(this.InvokeRequired) this.Invoke(mi); };
try it
txtFolderName.Invoke((MethodInvoker)delegate { string strFolderName = txtFolderName.Text; });
You will need to call your TextBox in the main thread.
tb.Invoke((MethodInvoker) delegate { tb.Text = "Update your text"; });
Try the following:
void DoWork(...) { YourMethod(); } void YourMethod() { if(yourControl.InvokeRequired) yourControl.Invoke((Action)(() => YourMethod())); else { //Access controls } }
Hope this help.
these are two more methods that I use.
//save the text value of txtFolderName into a local variable before run the backgroundworker. string strFolderName; private void btnExe_Click(object sender, EventArgs e) { strFolderName = txtFolderName.text; backgroundworker.RunWorkerAsync(); } private void backgroundworker_DoWork(object sender, DoWorkEventArgs e) { backgroundworkerMethod(strFolderName);//get the value from strFolderName ... } ---------------------------------------------------- private void btnExe_Click(object sender, EventArgs e) { backgroundworker.RunWorkerAsync(txtFolderName.text);//pass the value into backgroundworker as parameter/argument } private void backgroundworker_DoWork(object sender, DoWorkEventArgs e) { backgroundworkerMethod(e.Argument.ToString());//get the value from event argument ... }