Question : Backgroundworker and Text Box

Hello,

I am writing some text into a TextBox (on main form) from multiple threads. I read that prefered way to do it is to use BackgroundWorker. I found the following example and I don't know how to 'merge' it with my procedure which I am using to update the TextBox.

Example (http://msdn2.microsoft.com/en-ca/library/ms171728(VS.80).aspx):
************************************************************

' This event handler starts the form's
' BackgroundWorker by calling RunWorkerAsync.
'
' The Text property of the TextBox control is set
' when the BackgroundWorker raises the RunWorkerCompleted
' event.
 Private Sub setTextBackgroundWorkerBtn_Click( _
 ByVal sender As Object, _
 ByVal e As EventArgs) Handles setTextBackgroundWorkerBtn.Click
     Me.backgroundWorker1.RunWorkerAsync()
 End Sub


' This event handler sets the Text property of the TextBox
' control. It is called on the thread that created the
' TextBox control, so the call is thread-safe.
'
' BackgroundWorker is the preferred way to perform asynchronous
' operations.
 Private Sub backgroundWorker1_RunWorkerCompleted( _
 ByVal sender As Object, _
 ByVal e As RunWorkerCompletedEventArgs) _
 Handles backgroundWorker1.RunWorkerCompleted
     Me.textBox1.Text = _
     "This text was set safely by BackgroundWorker."
 End Sub


My Procedure which I use to update TextBox:
************************************

   Private Sub UpdateTextBox(ByVal LogData As String)
        Dim Stamp As String = Now.ToString("yyyy-MM-dd, HH:mm:ss")
        TextBox1.Text = TextBox1.Text & vbCrLf & "[" & Stamp & "] " & LogData
   End Sub

Could you guys help me with that and give me some explanation?

Thanks a lot!

Answer : Backgroundworker and Text Box

You need Delegates/Invoke() then...
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
    Private Delegate Sub UpdateDelegate(ByVal LogData As String)
 
    Private Sub UpdateTextBox(ByVal LogData As String)
        If Me.InvokeRequired() Then
            Me.Invoke(New UpdateDelegate(AddressOf UpdateTextBox), New Object() {LogData})
        Else
            Dim Stamp As String = Now.ToString("yyyy-MM-dd, HH:mm:ss")
            TextBox1.AppendText(vbCrLf & "[" & Stamp & "] " & LogData)
        End If
    End Sub
Random Solutions  
 
programming4us programming4us