Update Text Box Properly when Cross-threading in Visual Basic (VS 2012 V11)

后端 未结 2 1818
别跟我提以往
别跟我提以往 2021-01-22 15:58
  • 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?

    <
2条回答
  •  甜味超标
    2021-01-22 16:28

    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
    

提交回复
热议问题