2011-01-24 62 views
0

我在VB.NET 2010程序中正在進行跨線程通信/字段更新工作時遇到了一些麻煩。我試圖更新我的主窗體上的一個字段,每當我開始的線程拋出一個事件。下面是我的代碼的簡化版本:VB.NET中的跨線程通信和字段更新

我的主要形式有:

Public Class Main 
    ' stuff 

    ' Eventually, startProcessing gets called: 
    Private Sub startProcessing() 
     Dim processingClass = New MyProcessingClass("whatever") 
     AddHandler processingClass.processStatusUpdate, AddressOf handleProcessStatusUpdate 
     Dim processingThread = New Thread(AddressOf processingClass.process) 
     processingThread.Start() 
    End Sub 

    Private Sub handleProcessStatusUpdate(statusUpdate As String) 
     txtMainFormTextBox.Text = statusUpdate ' InvalidOperationException 
     ' "Cross-threaded operation not valid: Control 'txtMainFormTextBox' accessed from a thread other than the thread it was created on" 
    End Sub 
End Class 

這引起了該事件的類:

Public Class MyProcessingClass 
    Private whatever As String  

    Public Event processStatusUpdate(status As String) 

    Public Sub New(inWhatever As String) 
     whatever = inWhatever 
    End Sub 

    Public Sub process() 
     ' do some stuff 
     RaiseEvent processStatusUpdate(whatever) 
    End Sub 
End Class 

正如你所看到的,處理程序在我的主類沒有按」無法訪問我需要的TextBox,因爲它是由不同的線程觸發的(我認爲)。我已經嘗試了一些其他的方法來得到這個工作,其中包括:

  1. 移動事件處理程序MyProcessingClass,並通過引用(爲ByRef)到類路過txtMainFormTextBox
  2. MyProcessingClass而不是Main之內有實際的線程啓動。

這些都沒有奏效。顯然有一個我在這裏失蹤的概念。完成這件事的最好方法是什麼?謝謝!

回答

2

您需要通過調用BeginInvoke來更新UI線程上的文本框。


您應該使用BackgroundWorker component,這確實這一切爲您服務。
只需處理DoWorkProgressChanged事件。

+0

「BeginInvoke」的問題在於,當我使用它時我無法通過修改,所以我無法使用我的`statusString`。我會研究BackgroundWorker ... – 2011-01-24 01:31:56