程序有错,望高手祥解(附代码)
小弟照书上做的多线程的程序有错,不知怎么解决,代码如下:
Public Class Form1
Dim t2 As New System.Threading.Thread(AddressOf fun2)
Dim t1 As New System.Threading.Thread(AddressOf fun1)
Private Sub fun1()
Dim i As Integer
For i = 1 To 1000
Threading.Thread.Sleep(100)
ProgressBar1.Value = i
If i Mod 3 = 0 Then
Label1.Text = "能被3整除的整数是: " + i.ToString
End If
Next
End Sub
Private Sub fun2()
Dim i As Integer
For i = 1 To 1000
Threading.Thread.Sleep(100)
ProgressBar2.Value = i
If i Mod 4 = 0 Then
Label2.Text = "能被4整除的整数是: " + i.ToString
End If
Next
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Try
t1.Start()
t2.Start()
Catch ex As Exception
End Try
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
If t1.ThreadState <> Threading.ThreadState.Stopped Then
If t1.ThreadState = Threading.ThreadState.Suspended Then
t1.Resume()
End If
If t1.IsAlive Then
t1.Abort()
End If
End If
If t2.ThreadState <> Threading.ThreadState.Stopped Then
If t2.ThreadState = Threading.ThreadState.Suspended Then
t2.Resume()
End If
If t2.IsAlive Then
t2.Abort()
End If
End If
Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Button1.Text = "暂停 " Then
Try
t1.Suspend()
Catch err As Exception
End Try
Button1.Text = "恢复 "
Else
Try
t1.Resume()
Catch err As Exception
End Try
Button1.Text = "暂停 "
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
If t1.ThreadState = Threading.ThreadState.Suspended Then
t1.Resume()
End If
If t1.IsAlive Then
t1.Abort()
End If
Catch err As Exception
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If Button3.Text = "暂停 " Then
Try
t2.Suspend()
Catch err As Exception
End Try
Button3.Text = "恢复 "
Else
Try
t2.Resume()
Catch err As Exception
End Try
Button3.Text = "暂停 "
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Try
If t2.ThreadState = Threading.ThreadState.Suspended Then
t2.Resume()
End If
If t2.IsAlive Then
t2.Abort()
End If
Catch err As Exception
End Try
End Sub
End Class
我运行程序后,点击button5,系统就提示fun1何fun2中的“ProgressBar1.Value = i” 和“ProgressBar2.Value = i”有问题:
线程间操作无效: 从不是创建控件“ProgressBar1”的线程访问它。
线程间操作无效: 从不是创建控件“ProgressBar2”的线程访问它。
请问这怎么解决?
[解决办法]
大概是UI线程的问题,界面控件的创建是在UI线程里完成的,你在自己定义的线程里调用UI线程中的东西,应该算跨线程调用吧,参考一下这方面的资料吧,我也就知道这些了.