【问题标题】:VB.Net BackgroudworkerVB.Net 后台工作者
【发布时间】:2016-12-08 09:01:46
【问题描述】:

我使用 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

【问题讨论】:

  • ProgressBar 不会更新,因为它不在 GUI 线程上运行。您必须启用报告进度并从那里处理事件

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


【解决方案1】:

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

 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 事件中执行此操作)后,我们可以通过 ProgressChanged 事件跟踪其进度:在这里,我们使用由我们的工作 (DoWork) 修改的进度变量。您可以使用它来设置进度条值属性。最后,当一切完成后,我们将消息发送到适当的事件中,即 RunWorkerCompleted

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多