2016-03-01 71 views
1

我想字符串值文本框的值?跨線程操作無效

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的

交叉線程操作無效:從線程訪問的控件'textBox1',而不是它創建的線程。

+0

多線程很難,不要只是猜測你的方式。一個好的開始將是http://www.albahari.com/threading/。 – Luaan

回答

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; 
    }); 
}