Ivan Chan Ivan Chan - 4 months ago 16
Vb.net Question

vb.net Multithreading not working

I am learning how to do multithreading in vb.net. Here are the codes but it is not working.

the purpose of this program is to count the label1 and label2 from 0 to 100000 at the same time.

however, in the codes below, the label2 will only be counting up when label1 is finished. Can anyone teach me how to do it correctly?

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Thread1 As System.Threading.Thread

Thread1 = New System.Threading.Thread(AddressOf Me.Count1)
Thread1.Start()

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

Dim Thread2 As System.Threading.Thread

Thread2 = New System.Threading.Thread(AddressOf Me.Count2)
Thread2.Start()

End Sub

Private Sub InvokeIfRequired(del As [Delegate])

If InvokeRequired Then
Invoke(del)
Else
del.DynamicInvoke()
End If

End Sub

Private Sub AddText1()

Dim i As Integer = 0

Do Until i = 100000
i += 1
Label1.Text = i
Label1.Refresh()
Loop

End Sub

Private Sub AddText2()

Dim i As Integer = 0

Do Until i = 100000
i += 1
Label2.Text = i
Label2.Refresh()
Loop

End Sub

Private Sub Count1()

InvokeIfRequired(Sub()
AddText1()
End Sub)

End Sub

Private Sub Count2()

InvokeIfRequired(Sub()
AddText2()
End Sub)

End Sub

End Class

Answer

You should be testing to see whether an invoke is required when setting the Text of the label, not for the whole loop (and you don't need the refresh if it's in a separate thread)

Something like this:

Private Sub Count1()
    Dim i As Integer = 0

    Do Until i = 100000
        i += 1    
        InvokeIfRequired(Sub() Label1.Text = i.ToString())
    Loop

End Sub
Comments