如何动态计算后台工作者的进度条值?

时间:2012-10-15 09:53:57

标签: vb.net winforms

如何根据gridview总行数动态计算后台工作程序中的进度条值?

1 个答案:

答案 0 :(得分:3)

BackgroundWorker在与UI线程不同的线程上运行。因此,如果您尝试在后台工作程序的DoWork事件处理程序方法中修改表单上的任何控件,则会出现异常。

要更新表单上的控件,您有两个选择:

Imports System.ComponentModel

Public Class Form1
    Public Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
        ' This is not the UI thread.
        ' Trying to update controls here *will* throw an exception!!
        Dim wkr = DirectCast(sender, BackgroundWorker)

        For i As Integer = 0 To gv.Rows.Count - 1
            ' Do something lengthy
            System.Threading.Thread.Sleep(100)
            ' Report the current progress
            wkr.ReportProgress(CInt((i/gv.Rows.Count)*100))
        Next
    End Sub

    Private Sub bgw_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles bgw.ProgressChanged
        'everything done in this event handler is on the UI thread so it is thread safe

        ' Use the e.ProgressPercentage to get the progress that was reported
        prg.Value = e.ProgressPercentage
    End Sub
End Class
  • 调用委托以在您的UI线程上执行更新。
Imports System.ComponentModel

Public Class Form1
    Public Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
        ' This is not the UI thread.
        ' You *must* invoke a delegate in order to update the UI.
        Dim wkr = DirectCast(sender, BackgroundWorker)

        For i As Integer = 0 To gv.Rows.Count - 1
            ' Do something lengthy
            System.Threading.Thread.Sleep(100)
            ' Use an anonymous delegate to set the progress value
            prg.Invoke(Sub() prg.Value = CInt((i/gv.Rows.Count)*100))
        Next
    End Sub
End Class



注意:您还可以查看my answer相关问题以获取更详细的示例。