Tuesday, April 8, 2008

Updating a Windows Application Textbox in a multithreading environment

The following is based on the article from MSDN website.

Basically, it says that we need to declare a delegate:

Delegate Sub SetTextCallback([text] As String)
Then in the routine that updates the textbox will check if it is in the thread id and will transfer the control to the thread that owns the textbox.

Private Sub SetText(ByVal [text] As String)

' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.textBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Me.textBox1.Text = [text]
End If
End Sub

No comments: