Post subject: Thread-Safe call for Updating Windows Form Object (VB.Net)
Editor
Joined: 3/31/2010
Posts: 1466
Location: Not playing Puyo Tetris
I am trying to make a program that will use a second thread to get a list of files, and show that list into a listbox. The listing part works great. But, I can't get the second thread to behave. When I try and use a second thread, the process seems to work until I get to the add to list box function. I get the error message: Cross-thread operation not valid: Control 'lstFiles' accessed from a thread other than the thread it was created on. Code I am using to update the list box:
 For Each path In FileList
            lstFiles.Items.Add(path)
Next
I know I am supposed to invoke a callback but I have no idea how to do that.
When TAS does Quake 1, SDA will declare war. The Prince doth arrive he doth please.
Joined: 7/2/2007
Posts: 3960
I have no idea what language and UI framework you're using here, but typically you can only make changes to the UI in the "main" thread. Your framework may well have a function whose job it is to re-invoke a given function in the main thread. For example, in wxWidgets, instead of doing
listBox.AddItems(items)
you would instead do
wx.CallAfter(listBox.AddItems, items)
. The CallAfter function takes as its first argument the function to call, and as its remaining arguments the parameters to pass to that function. You should check and see if your own UI framework has a similar function.
Pyrel - an open-source rewrite of the Angband roguelike game in Python.
Editor
Joined: 3/31/2010
Posts: 1466
Location: Not playing Puyo Tetris
I decided since I am not going to be updating the object (list) outside of the second thread, I can tell it to use IgnoreThreadSafety. The second thread does it's job as it's supposed to and the GUI is running and updating all the same. I guess that works since I know what the code will be doing at the time of the listing. Derakon, I am using Visual Basic.Net (VB.Net)
When TAS does Quake 1, SDA will declare war. The Prince doth arrive he doth please.
Editor, Emulator Coder, Site Developer
Joined: 5/11/2011
Posts: 1108
Location: Murka