2012-10-15 2 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 



NB : 또한보다 상세한 예를 들어 관련 질문에 my answer을 볼 수 있습니다.

+0

감사합니다. Alex Essifie –