Cross reference operations error

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

This is code in C # which, when executed, causes an invalid cross-thread execution error for listBox1, which is a list in my form. Maybe guys please tell me why? I also use the invokeRequired method and do not change the contents of the list.

0
source share
3 answers

InvokeRequired reports that Invoke is required to actually access the item. This does not make 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(); } 
+5
source

InvokeRequired just checks if Invoke is required. You found it necessary, but did not call Invoke!

+3
source

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 Windows Forms Security

+2
source

Source: https://habr.com/ru/post/1341955/


All Articles