2

我正在尝试在 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 的进度条。

任何帮助将不胜感激。

4

2 回答 2

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
于 2013-03-11T17:51:58.660 回答
2

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

BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.RunWorkerAsync()

Now your BackgroundWorker1_ProgressChanged will be called in the context of the UI Thread and you can set the progressbar value

Of course, when you call ReportProgress to raise the ProgressChanged event, you need to pass the percentage of work done so far.

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
于 2013-03-11T18:13:16.573 回答