1

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

4

1 回答 1

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



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

于 2012-10-15T13:45:05.247 回答