Click here to Skip to main content
15,908,776 members
Please Sign up or sign in to vote.
4.00/5 (3 votes)
See more:
Hello!

I got an exception called cross thread operation invalid in ma test programme.I knw the error.But I dnt knw how to fix it.Please comment on this matter.Thank you all.

Here is my simple code:

private void button1_Click(object sender, EventArgs e)
       {
           Thread thr1 = new Thread(adddata);
           thr1.Start();
           //if (thr1.IsAlive)
             //  addvalue();
       }
       private void adddata() {
           for (int i = 0; i < 20;i++) {
               listBox1.Items.Add(i);
           }
       }
       private void addvalue() {
           int a = 0;
           for (int j = 0; j < 20;j++ ) {
              listBox2.Items.Add(listBox1.Items[0].ToString());
           }
       }


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 22-Apr-11 20:31pm
v4

1 solution

Most controls dont allow to be accessed from a thread other than the UI thread. Therefore, these controls have an invoke method which can be called from a different thread.

Your AddData could be written like this so that it will also function from a different thread.

C#
public void AddData()
{
  if (this.InvokeRequired)
  {
    // call method on the ui thread...
    this.Invoke(new MethodInvoker(AddData));
  }
  else
  {
    // In the ui thread
    for (int i = 0; i < 20; i++)
    {
      listBox1.Items.Add(i);
    }
  }
}


Hope this helps.
 
Share this answer
 
v2
Comments
Sameera Fonseka 23-Apr-11 2:23am    
Thank you very much for havn ur knd attntn on ths prblm and ur advcs.Thank u.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900