1
如何根據gridview總行數動態統計backgound worker中的進度條值?如何動態計算後臺工作進度條值?
如何根據gridview總行數動態統計backgound worker中的進度條值?如何動態計算後臺工作進度條值?
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
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到一個相關的問題進行更詳細的例子。
謝謝Alex Essifie –