private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ParameterizedThreadStart(startRequest));
t.Start(textBox1);
}
void startRequest(object textBox1)
{
textBox1.Text = "hello";
}
这里我得到一个错误,即textBox1没有属性Text,在主线程中一切正常,但在新线程中我得到一个错误,如何解决这个问题?
答案 0 :(得分:4)
在使用Text属性之前,您必须将object
强制转换为TextBox
类型。
void startRequest(object textBox1)
{
MethodInvoker mi = delegate
{
TextBox tempTextBox = textBox1 as TextBox;
if (tempTextBox != null)
tempTextBox.Text = "hello";
};
if (this.InvokeRequired)
this.Invoke(mi);
}
如果转换失败,最好检查null。
答案 1 :(得分:1)
对象没有属性,你需要type cast
对象TextBox
,你不能访问文本框,因为你当前的线程不是GUI thread
。您可以使用MethodInvoker
在GUI线程中调用代码,如下所示。
void startRequest(object textBox1)
{
MethodInvoker mi = delegate {
((TextBox) textBox1).Text = "hello";
}
if(InvokeRequired)
this.Invoke(mi);
}
答案 2 :(得分:1)
您无法从UI线程以外的线程访问UI组件。你会在这里得到例外
tempTextBox.Text = "hello";
如果您尝试从另一个线程执行此操作。