1

I want to fill textbox1 with string values

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

but at when thread start filling textbox with value it responded with error

Cross-thread operation not valid: Control 'textBox1' accessed from a thread >other than the thread it was created on.

GLOBAL TECH
  • 71
  • 10
  • Multi-threading is hard, don't just guess your way around. A good start would be http://www.albahari.com/threading/. – Luaan Mar 01 '16 at 09:10

1 Answers1

1

You cannot access UI controls other than UI thread. Try following code.

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;
    });
}
Sampath
  • 1,173
  • 18
  • 29