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:

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);
           //if (thr1.IsAlive)
             //  addvalue();
       private void adddata() {
           for (int i = 0; i < 20;i++) {
       private void addvalue() {
           int a = 0;
           for (int j = 0; j < 20;j++ ) {

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

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.

public void AddData()
  if (this.InvokeRequired)
    // call method on the ui thread...
    this.Invoke(new MethodInvoker(AddData));
    // In the ui thread
    for (int i = 0; i < 20; i++)

Hope this helps.
Share this answer
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