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 –