Here is my question in short: How do I use the BackGroundWorker (or InvokeRequired method) to make thread-safe calls to append text to a text box?
<
Change:
Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "\" & e.Name, True)
TextBox3.ApendText("[New Text]") ' This line causes an error
End Sub
To:
Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "\" & e.Name, True)
AppendTextBox(TextBox3, "[New Text]")
End Sub
Private Delegate Sub AppendTextBoxDelegate(ByVal TB As TextBox, ByVal txt As String)
Private Sub AppendTextBox(ByVal TB As TextBox, ByVal txt As String)
If TB.InvokeRequired Then
TB.Invoke(New AppendTextBoxDelegate(AddressOf AppendTextBox), New Object() {TB, txt})
Else
TB.AppendText(txt)
End If
End Sub
Here's an updated, simplified version that uses an anonymous delegate:
Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
Dim filename As String = System.IO.Path.Combine(TextBox2.Text, e.Name)
Try
My.Computer.FileSystem.CopyFile(e.FullPath, filename, True)
TextBox3.Invoke(Sub()
TextBox3.AppendText("[New Text]")
End Sub)
Catch ex As Exception
Dim msg As String = "Source: " & e.FullPath & Environment.NewLine &
"Destination: " & filename & Environment.NewLine & Environment.NewLine &
"Exception: " & ex.ToString()
MessageBox.Show(msg, "Error Copying File")
End Try
End Sub