先看段代码:非常典型的简单多线程。
Dim t1 As Thread
Dim t2 As Thread
Private Sub Process1()
Dim i As Integer = 1
Do While True
ProgressBar1.Value = i
i += 1
If i = 10000 Then
i = 1
End If
Loop
'为了让用户看清进度条的进度,将线程处理速度变慢
Thread.Sleep(2)
End Sub
Private Sub Process2()
Dim i As Integer = 1
Do While True
ProgressBar2.Value = i
i += 1
If i = 10000 Then
i = 1
End If
Loop
'为了让用户看清进度条的进度,将线程处理速度变慢
Thread.Sleep(2)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
t1 = New Thread(AddressOf Process1)
t1.Start()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
t1.Abort()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
t2 = New Thread(AddressOf Process2)
t2.Start()
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
t2.Abort()
End Sub
为什么这段代码在 VS2003里正确运行,在VS2005中就不对了呢?发生了以下错误:Cross-thread operation not valid: Control 'ProgressBar1' accessed from a thread other than the thread it was created on.