0

Hi i have a program that run threads and updates the UI in the process. I have used .invokerequired for a safe threading and everything is running OK. In one of the threads it is necessary to use the value of an item in the listbox which is created in another thread (ListBox2.Items(index)) and i'm currently doing that with dim item1 as integer =ListBox2.Items(index). Now the program is running fine and showing no exceptions or error messages, however, if i add a watch of the same line i get the following message + AccessibilityObject {"Cross-thread operation not valid: Control 'ListBox2' accessed from a thread other than the thread it was created on."} System.InvalidOperationException.

Is it normal? is there a way to safely get a value of an item in the listbox which is located on another thread?

user1937198
  • 4,987
  • 4
  • 20
  • 31
user2334436
  • 949
  • 5
  • 13
  • 34
  • Use delegates, or just use a background worker. – Trevor May 05 '13 at 06:54
  • You can check out more here: http://stackoverflow.com/questions/3969476/how-to-pass-a-variable-to-another-thread – Trevor May 05 '13 at 07:00
  • I could not use a delegate to get the value of (ListBox2.Items(index)). i don't need any changes to the UI, i just want to get the value of ListBox2.Items(index) in a thread- safe manner. – user2334436 May 05 '13 at 09:04
  • Dont create ui elements in threads, use control.invoke to create and access them on the ui thread. – user1937198 May 05 '13 at 12:20

1 Answers1

0

To answer the question to about cross thread exception, this is normal and you are not allowed to access ui elements from a different thread from the one they where created on. To fix this you need to use control.invoke() to execute a lambda expression to run the access code on the thread that created the listbox.

Dim item1 as Integer
If ListBox2.InvokeRequired then
    Listbox2.Invoke(Sub() Item1 = ListBox2.Items(Index))
Else
    Item1 = ListBox2.Items(Index)
End If
user1937198
  • 4,987
  • 4
  • 20
  • 31