VB.Net - 从后台工作者更新进度条

时间:2013-03-11 17:47:21

标签: vb.net visual-studio-2010 progress-bar backgroundworker

我正在尝试在VB.Net中构建一个日志解析器,它将获取IIS日志并将它们插入到数据库中。从来没有真正完成一个完整的桌面应用程序,我遇到了一些绊脚石,所以请原谅我,如果我的问题是一个非常不知情的;我正在学习跑步时走路。

我正在使用的代码如下所示:

 Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    MyBase.OnLoad(e)
    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim logfile = "C:\ex111124.log"
    Dim FileLength As Long = New System.IO.FileInfo(logfile).Length
    logFileLabel.Text = logfile

    Dim objReader As New System.IO.StreamReader(logfile)
    Do While objReader.Peek() <> -1
        OngoingLog.AppendText(objReader.ReadLine)
        'BackgroundWorker1.ReportProgress(e.percentProgress)
        Loop()
    objReader.Close()
    objReader = Nothing

End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    'Me.crunchingProgress.Value = e.ProgressPercentage
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    Close()
End Sub

因此该函数工作,当这个窗口打开时,它开始读取日志文件并更新当前读取的所有行的文本框,但我也希望它更新我的主线程中的进度条crunchingProgress。 / p>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    Invoke(Sub()
        Me.crunchingProgress.Value = e.ProgressPercentage
    End Sub)
End Sub

答案 1 :(得分:2)

您没有将BackgroundWorker设置为报告进度(WorkerReportsProgress

BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()

现在您的BackgroundWorker1_ProgressChanged将在UI线程的上下文中调用,您可以设置进度条值

当然,当您调用ReportProgress来引发ProgressChanged事件时,您需要传递到目前为止完成的工作百分比。

Using objReader As New System.IO.StreamReader(logfile)
    Do While objReader.Peek() <> -1
        Dim line = objReader.ReadLine()
        OngoingLog.AppendText(line)
        Dim pct = Convert.ToInt32((100 * line.Length) / FileLength )
        BackgroundWorker1.ReportProgress(pct)
    Loop
End Using