【问题标题】:C# Get Textbox value in backgroundworker dowork eventC#在backgroundworker dowork事件中获取文本框值
【发布时间】:2013-04-02 09:32:23
【问题描述】:
在我的 Windows 窗体应用程序中,我有一个 textbox 和 backgroundworker 组件。在backgroundworker 的dowork 事件中,我试图访问文本框的值。我怎样才能做到这一点?当我尝试访问文本框的值时,dowork 事件处理程序代码中出现以下异常:
Cross-thread operation not valid: Control 'txtFolderName' accessed from a thread other than the thread it was created on`
【问题讨论】:
标签:
c#
multithreading
winforms
thread-safety
backgroundworker
【解决方案1】:
试试这个
txtFolderName.Invoke((MethodInvoker)delegate
{
string strFolderName = txtFolderName.Text;
});
【解决方案2】:
你只能在GUI线程中访问textbox / form controls,你可以这样做。
if(txtFolderName.InvokeRequired)
{
txtFolderName.Invoke(new MethodInvoker(delegate { name = txtFolderName.text; }));
}
【解决方案3】:
您需要使用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);
};
【解决方案4】:
您必须在主线程上调用您的 TextBox。
tb.Invoke((MethodInvoker) delegate
{
tb.Text = "Update your text";
});
【解决方案5】:
试试这个:
void DoWork(...)
{
YourMethod();
}
void YourMethod()
{
if(yourControl.InvokeRequired)
yourControl.Invoke((Action)(() => YourMethod()));
else
{
//Access controls
}
}
希望得到帮助。
【解决方案6】:
这是我使用的另外两种方法。
//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
...
}