0
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,在主线程中一切正常,但是在新线程中我得到一个错误,如何解决这个问题?

4

3 回答 3

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。

于 2012-12-06T09:32:40.730 回答
1

Object does not have property, You need to type cast object to TextBox, you wont be able to access text box though as your current thread is not GUI thread. You can use MethodInvoker To invoke the code in GUI thread as follow.

void startRequest(object textBox1)
{
    MethodInvoker mi = delegate {         
        ((TextBox) textBox1).Text = "hello";
    }
    if(InvokeRequired)
       this.Invoke(mi);
}
于 2012-12-06T09:33:31.660 回答
1

您不能从 UI 线程以外的线程访问 UI 组件。你会在这里得到例外

tempTextBox.Text = "hello";

如果您尝试从另一个线程执行此操作。

于 2012-12-06T09:36:32.550 回答