5

在我的 Windows 窗体应用程序中,我有一个textboxbackgroundworker组件。如果我试图访问文本框的值doworkbackgroundworker我怎样才能做到这一点?当我尝试访问文本框的值时,dowork 事件处理程序代码中出现以下异常:

Cross-thread operation not valid: Control 'txtFolderName' accessed from a thread other than the thread it was created on`
4

6 回答 6

6

您只能textbox / form controlsGUI 线程中访问,您可以这样做。

if(txtFolderName.InvokeRequired)
{
    txtFolderName.Invoke(new MethodInvoker(delegate { name = txtFolderName.text; }));
}
于 2013-04-02T09:34:08.537 回答
3

试试这个

  txtFolderName.Invoke((MethodInvoker)delegate
            {
                string strFolderName = txtFolderName.Text;
            });  
于 2013-04-02T09:38:03.883 回答
2

您需要使用MethodInvoker。像:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object sender, DoWorkEventArgs e)
 {
       MethodInvoker mi = delegate { txtFolderName.Text = "New Text"; };
       if(this.InvokeRequired)
           this.Invoke(mi);
 };
于 2013-04-02T09:33:58.300 回答
1

您将不得不在主线程上调用您的 TextBox。

tb.Invoke((MethodInvoker) delegate
{
    tb.Text = "Update your text";
});
于 2013-04-02T09:34:16.933 回答
1

试试这个:

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

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

希望这有帮助。

于 2013-04-02T09:35:20.087 回答
0

这是我使用的另外两种方法。

    //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
        ...
    }
于 2015-01-09T09:37:17.620 回答