VB.Net Backgroudworker

时间:2016-12-08 09:01:47

标签: vb.net visual-studio-2013 backgroundworker postmortem-debugging

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

我正在使用BackgroundWorker,它看起来与我认为应该的方式不同。

我不明白为什么我的程序在处理了名为arFileName的ArrayList中的第一个条目后停止了。

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

1 个答案:

答案 0 :(得分: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 启动backgroundworker(我在 Form_Load 事件中)后,我们可以通过 ProgressChanged 事件跟踪其进度:在这里,我们使用由我们的工作修改的进度变量( DoWork )。您可以使用它来设置进度条值属性。最后,完成所有操作后,我们将消息发送到正确的事件中,即 RunWorkerCompleted