Click here to Skip to main content
15,921,941 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
Hi,

How to apply multithreading in a windows forms.I just need to print 1 to 100 numbers parallely in 2 listboxes.How to do that?
Posted

I suggested you some articles here
Multithreading doesn't work[^]
Did you try anything?
 
Share this answer
 
Yes sir..but that articles are related with console applications..
 
Share this answer
 
You could do something like:

System.Threading.Tasks.Parallel.For(0, 100, i =>
        {
            listBox1.Items.Add(i)
            listBox2.Items.Add(i)
        });


But I will tell you up front that this answer is currently wrong because it will fail when it tries to access the listboxes because they will likely need to be accessed by using something like ...

Private Delegate Sub dlgListBox1Update(ByVal text As String)
 
Sub updateListBox1(ByVal text As String)
    If ListBox1.InvokeRequired = True Then
        Dim d As New dlgListBox1Update(AddressOf updateListBox1)
        ListBox1.Invoke(d, text)
    Else
        ListBox1.Items.Add(text)
    End If
End Sub

Private Delegate Sub dlgListBox2Update(ByVal text As String)
 
Sub updateListBox2(ByVal text As String)
    If ListBox2.InvokeRequired = True Then
        Dim d As New dlgListBox2Update(AddressOf updateListBox2)
        ListBox2.Invoke(d, text)
    Else
        ListBox2.Items.Add(text)
    End If
End Sub

System.Threading.Tasks.Parallel.For(0, 100, i =>
        {
            updateListBox1(i.toString)
            updateListBox2(i.toString)
        });


You need to use the delegates and the update subroutines in order to ensure that you adjust to the correct thread for actually updating the listboxes ... that's the fundamental challenge with multithreaded applications (and why most examples use the console so they can focus on the example and not creating delegates).

Of course the next problem you'll have is when you try and change variables within your different threads ... if you use global variables then you'll need to lock them to ensure you don't change them from multiple threads.

Hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900