Tutorial :crossthread operations error


      if (listBox1.InvokeRequired)         {             listBox = new StringBuilder(this.listBox1.Text);         }  

This is the code in c# which when executed produces an invalid cross thread operation error for listBox1 which is a listbox in my form. Could u guys please tell me why?? I am using the invokeRequired method too and am not changing the contents of the listbox either.


InvokeRequired only tells you that an Invoke is necessary in order to validly access the element. It doesn't make the access legal. You must use the invoke method to push the update to the appropriate thread

Action update = () => listbox = new StringBuilder(this.listBox1.Text);  if (listBox1.InvokeRequired) {    listBox1.Invoke(update);  } else {    update();  }  


InvokeRequired simply checks to see if Invoke is required. You found it's required, yet didn't call Invoke!


Your code should run when InvokeRequired is false

delegate void SetListBoxDelegate();     void SetListBox()  {      if(!InvokeRequired)      {          listBox = new StringBuilder(this.listBox1.Text);      }       else           Invoke(new SetListBoxDelegate(SetListBox));   }   

Edit: Check out Making Windows Forms thread safe

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »