请有人能帮助我吗?我对VB.net和线程都很陌生,所以我只想弄清楚发生了什么。
当我调试这个时,我收到了错误
线程操作无效:从a访问控制'ProgressBar1' 除了创建它的线程以外的线程。
我有点迷失为什么错误发生或如何修复它。我必须将进度条放在一个单独的线程中,否则GUI崩溃
Private Sub InstallTheAgent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InstallTheAgent.Click
MsgBox("Click OK to continue to install the Agent")
Dim t As Thread
t = New Threading.Thread(AddressOf WorkInstallAgent)
t.Start()
End Sub
Private Sub WorkInstallAgent()
ProgressBarThread()
Dim DeviceLines As String() = IO.File.ReadAllLines(DynPath & "\machines.txt")
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = DeviceLines.Length
Using myReader As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(DynPath & "\machines.txt")
ProgressBarThread()
Do While myReader.Peek() >= 0
Dim computerName As String = myReader.ReadLine
If My.Computer.Network.Ping(computerName) = True Then
Call CopyAgent(computerName)
Call InstallAgent(computerName)
Call Agent(computerName)
Call RemoveTempSoftware(computerName)
End If
ProgressBar1.Value = ProgressBar1.Value + 1
Loop
End Using
MsgBox("Installation of the Agent Complete")
ProgressBar1.Value = 0
End Sub
Public Sub ProgressBar()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf ProgressBar))
Else
Dim DeviceLines As String() = IO.File.ReadAllLines(DynPath & "\machines.txt")
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = DeviceLines.Length
End If
End Sub
Public Sub ProgressBarThread()
Dim p As Thread
p = New Threading.Thread(AddressOf ProgressBar)
p.Start()
End Sub
答案 0 :(得分:0)
进度条在GUI线程上。如果您尝试从其他线程访问它,则会发生此错误。
尝试使用背景工作者。检查此链接: http://www.java2s.com/Code/VB/GUI/BackgroundWorkerDemo.htm
答案 1 :(得分:0)
很抱歉,但您的代码很乱。您可以在所有这些代码中混合数据处理和进度显示。
你调用一个线程(ProgressBarThread),它将调用一个可能自动调用的子进行...只需一个操作?为什么一个线程?
由于只有一个进度条,因此无法启动多个线程并为每个线程显示。
或者......快速修复:每次访问进度条时都使用调用:Me.Invoke(sub()ProgressBar1.Minimum = 12)