使用线程的文本框值?跨线程操作无效

时间:2016-03-01 08:54:29

标签: c# multithreading

我想用字符串值填充textbox1

   public  void CallToChildThread()
    {
        string test1 = "this is 1st";
        string test2 = "this is 2nd";
        string test3 = "this is 3rd";
        textBox1.Text = test1;   //Cross-thread operation not valid
        int sleepfor = 5000;
        Thread.Sleep(sleepfor);
       textBox1.Text = "Child Thread 1 Paused for {0} seconds '"+sleepfor/1000+"' ";
        textBox1.Text = test3;
        textBox1.Text = test4;
        Thread.Sleep(sleepfor);
        textBox1.Text = "Child Thread 2 Paused for {0} seconds '" + sleepfor / 1000 + "' ";
        textBox1.Text = test5;
    }
    private Thread myThread = null;
    private void button1_Click(object sender, EventArgs e)
    {
        this.myThread =
     new Thread(new ThreadStart(this.CallToChildThread));
        this.myThread.Start();
    }

但是当线程开始用值填充文本框时,它会回复错误

  

跨线程操作无效:控制'textBox1'从线程>访问,而不是创建它的线程。

1 个答案:

答案 0 :(得分:1)

您无法访问UI线程以外的UI控件。请尝试以下代码。

public  void CallToChildThread()
{
    string test1 = "this is 1st";
    string test2 = "this is 2nd";
    string test3 = "this is 3rd";

    this.Invoke((MethodInvoker)delegate
    {        
        textBox1.Text = test1;   //Cross-thread operation not valid
    });

    int sleepfor = 5000;
    Thread.Sleep(sleepfor);

    this.Invoke((MethodInvoker)delegate
    { 
   textBox1.Text = "Child Thread 1 Paused for {0} seconds '"+sleepfor/1000+"' ";
    textBox1.Text = test3;
    textBox1.Text = test4;
    });

    Thread.Sleep(sleepfor);

    this.Invoke((MethodInvoker)delegate
    { 
    textBox1.Text = "Child Thread 2 Paused for {0} seconds '" + sleepfor / 1000 + "' ";
    textBox1.Text = test5;
    });
}