views:

132

answers:

3
      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.

+3  A: 

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

John Saunders
+5  A: 

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();
}
JaredPar
I thought the brace style at MS was opening brace on separat line?!? ;)
Mitch Wheat
@Mitch, MS doesn't have an official style but a lot of groups do use the brace on newline rule. It's also my preference for C style languages. But when I post code to the web I use the same line style to make the examples more succinct :)
JaredPar
The Mono project actually specifies the same-line practice for all its source, going completely against the Microsoft/StyleCop guidelines - and it's not the only thing they do contrastingly. Then again, why should they follow the Microsoft example? Makes me wonder whether they just want to spite MS developers, however. :P The same-line style personally seems a bit ugly to me, though maybe that's just habbit. Either way, it's certainly *acceptable*.
Noldorin
+2  A: 

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

Rashmi Pandit