I recently start learning about multi threading. I'd want to know is my code right or wrong.
VB Code:
Public Class Form1 Private Delegate Sub SetTextCallBack(ByVal val As Integer) Dim t As Threading.Thread Dim i As Integer = 0 Private Sub SetText(ByVal val As Integer) If Me.Label1.InvokeRequired Then Dim d As New SetTextCallBack(AddressOf SetText) 'I have used Me.Label1.begininvoke; Me.Label1.invoke; Me.begininvoke; Me.invoke 'The result is same 'The only difference is if doloop didn't sleep, begininvoke will stop responding 'Me.BeginInvoke(d, val) Me.Invoke(d, val) Else Label1.Text = val End If End Sub Private Sub doLoop() While i < 10000 If i > 9000 Then i = 0 End If If i Mod 100 = 0 Then Me.SetText(i) Threading.Thread.Sleep(100) End If i += 1 End While MessageBox.Show("Finished") End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Me.doLoop() t = New Threading.Thread(New Threading.ThreadStart(AddressOf doLoop)) t.Start() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 't.Abort() 'I've read some article that I should not use this. 'Me.Text = "Button2" i = 10000 t.Join() 'Or use t=nothing End Sub End Class
My question is: Does this code right? It seems that doloop procedure must sleep for a while if I want my UI thread keep responding.




Reply With Quote