Question Access Listbox from ThreadPool

sollniss

Member
Joined
Aug 5, 2008
Messages
12
Programming Experience
3-5
I have two List(Of String) binded with two ListBoxes in the Form.Load event.
Then I have a ThreadPool wich fills these Lists, but the ListBoxes didn't show the items from the Lists.

Can someone halp me to fix this?
 
You can add the items from the thread by invoking a method on the thread the UI control belongs to, invoking is done through a delegate pointing to the method, for example:
VB.NET:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(AddressOf FillByThreadPool))
End Sub

Private Delegate Sub AddCallback(ByVal items() As Object)

Private Sub FillByThreadPool(ByVal state As Object)
    Dim l As New List(Of String)
    For i As Integer = 1 To 10
        l.Add(i.ToString)
    Next
    Me.ListBox1.Invoke(New AddCallback(AddressOf Me.ListBox1.Items.AddRange), New Object() {l.ToArray})
End Sub
 
Thanks, but my Lists becoming bigger and bigger and if I use this code example I need to clear the ListBox everytime before I fill it.

Is there any possibility to do this without clearing, adding, clearing, adding... ?

BTW. The ListBox will be appended several thousand times.
 
You have to use the same technique either way to modify the UI control from a different thread.
VB.NET:
Private SafeAdd As Threading.WaitCallback

Private Sub AddItems(ByVal state As Object)
    For i As Integer = 1 To 10
        Me.ListBox1.Invoke(SafeAdd, i.ToString)
    Next
End Sub

Private Sub testForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    SafeAdd = New Threading.WaitCallback(AddressOf Me.ListBox1.Items.Add)
    Threading.ThreadPool.QueueUserWorkItem(AddressOf AddItems)
End Sub
 
Back
Top