0

我使用 Visual Studio 2013 for Visual Basic,我正在努力调试我的多线程程序。

我正在使用 BackgroundWorker,它的工作方式似乎与我认为的不同。

我不明白为什么我的程序在只处理了 ArrayList 中名为arFileName.

BackgroundWorker1.DoWork 过程中的For Each语句无法遍历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
4

1 回答 1

0

必须设置后台工作程序以报告其进度

 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

如您所见,我定义了一个进度变量,它将跟踪已完成工作的百分比。在我们使用RunWorkerAsync启动后台工作程序(我在Form_Load事件中执行)之后,我们可以通过ProgressChanged事件跟踪它的进度:在这里,我们使用由我们的工作(DoWork)修改的进度变量。您可以使用它来设置进度条值属性。最后,当一切都完成后,我们将消息发送到适当的事件中,即RunWorkerCompleted

于 2016-12-08T09:36:13.313 回答