I’ve been searching the web for a way to do this without much success, so here’s the question.
How do add items to a listbox in a separate thread, so that it doesn’t freeze up the ui?
There are roughly 5-15k items each time added to the listboxes, and it freezes the ui for 5-12 seconds each time.
The form has 4 listboxes, the information for these listboxes is first created, and added to a 2D array (doing it this way makes it easier to keep track of all information that belongs together in 1 row). after which i loop over that 2D array, adding the 4 columns in 1 row to it’s respective listbox.
eg.
for (int n = 0; n < 7500; n++)
{
listBox1.Items.Add(itemList[n, 0].ToString());
listBox2.Items.Add(itemList[n, 1].ToString());
listBox3.Items.Add(itemList[n, 2].ToString());
listBox4.Items.Add(itemList[n, 3].ToString());
}
As stated before, how to use a thread other than the UI to update these listboxes to prevent unnecessary freezing of the ui
You can take a different approach and use a virtual ListView instead. When a ListView is “virtual”, you are responsible for maintaining item lists and telling ListView what to display on paint events. This way you can update your lists in any thread-safe way you’d like and ListView will only ask of you “what to draw on screen” rather than a full list of items. That’s actually the preferred method when obtaining list of all items is very costly.
See the documentation on VirtualMode:
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx
UPDATE: Since you mentioned that you need it for debugging I also suggest you to use debug output (
Debug.WriteLine()) which could be more suitable for the job. It’s optimized, it’s thread safe, it doesn’t block anything but itself and the best part is it doesn’t affect performance of release builds.And in case you need a more performant output you can redirect your debugging output to anywhere you like.