5

In my windows forms application I have a textbox and backgroundworker component. In dowork event of the backgroundworker I am trying to access value of the textbox. How can i do that? I'm getting following exception in dowork event handler code when I try to access value of the textbox:

Cross-thread operation not valid: Control 'txtFolderName' accessed from a thread other than the thread it was created on`
Mikhail
  • 20,685
  • 7
  • 70
  • 146
user1941944
  • 331
  • 2
  • 6
  • 16

6 Answers6

6

You can only access textbox / form controls in GUI thread, you can do so like that.

if(txtFolderName.InvokeRequired)
{
    txtFolderName.Invoke(new MethodInvoker(delegate { name = txtFolderName.text; }));
}
Adil
  • 146,340
  • 25
  • 209
  • 204
3

try this

  txtFolderName.Invoke((MethodInvoker)delegate
            {
                string strFolderName = txtFolderName.Text;
            });  
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83
2

You need to use MethodInvoker. Like:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object sender, DoWorkEventArgs e)
 {
       MethodInvoker mi = delegate { txtFolderName.Text = "New Text"; };
       if(this.InvokeRequired)
           this.Invoke(mi);
 };
Habib
  • 219,104
  • 29
  • 407
  • 436
1

You will have to invoke your TextBox on the main thread.

tb.Invoke((MethodInvoker) delegate
{
    tb.Text = "Update your text";
});
animaonline
  • 3,715
  • 5
  • 30
  • 57
1

Try This:

void DoWork(...)
{
    YourMethod();
}

void YourMethod()
{
    if(yourControl.InvokeRequired)
        yourControl.Invoke((Action)(() => YourMethod()));
    else
    {
        //Access controls
    }
}

Hope This Help.

Sharique Ansari
  • 1,458
  • 1
  • 12
  • 22
0

this is the another 2 methods 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
        ...
    }
YHTAN
  • 626
  • 5
  • 19