我使用Visual Studio 2013进行Visual Basic,我正在努力调试我的多线程程序。
我正在使用一个背景工作者,它似乎与我认为应该如何有所不同。
我不明白为什么我的程序仅处理我的Arraylist中的第一个条目叫arFileName
。
For Each
在BackgroundWorker1.Dowork过程中的语句在以下代码中未能通过整个arFileName
迭代:
Private Sub btnRun_Click(sender As Object, e As EventArgs) Handles btnSelectCsv.Click
'arFileName is ArrayList and it has enormous counts
ProgressBar1.Maximum = arFileName.Count
Me.Cursor = Cursors.WaitCursor
'Do background
BackgroundWorker1.RunWorkerAsync()
Me.Cursor = Cursors.Arrow
MessageBox.Show("Finished!", "info", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork
Dim arNotFoundFile As New ArrayList
'Confirm file exists
For Each filename As String In arFileName ' Here!
If Not IO.File.Exists(filename) Then
arNotFoundFile.Add(filename)
ProgressBar1.Value = ProgressBar1.Value + 1
End If
Next
End Sub
必须设置后台工作者以报告其进度
BackgroundWorker1.WorkerReportsProgress = True
那么,典型的实现可能如下:
Dim progress As Integer = 0
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
While (progress < 100)
' YOUR CODE HERE
progress += 1
BackgroundWorker1.ReportProgress(progress)
End While
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' YOUR PROGRESSBAR VALUE HERE, USING progress VARIABLE
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Work completed")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()
End Sub
您可以看到,我已经定义了 progress 变量,这将跟踪完成的工作百分比。在我们使用 runworkerAsync form_load 事件中启动背景工作者(我将其进行到 form_load 事件)之后,我们可以通过 progressChangedChanged 事件来跟踪其进度:在这里,我们使用了由我们的工作修改的进度变量( dowork )。您可以使用它来设置progressbar值属性。最后,完成所有操作后,我们将消息发射到适当的事件中,即 runworkercompleted