2012-10-15 71 views

回答

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到一個相關的問題進行更詳細的例子。

+0

謝謝Alex Essifie –