How should I call a delegate from a BackgroundWorker?

69 Views Asked by At

I've created a delegate to have a log, the RichTexbox is visible and I want to call the delegate from a BackgroundWorker (DoWork) but is not working.

What should I change to this?

Public Class Form1
    Public Delegate Sub WriteRtbLogDelegate(ByVal Texto As String, ByVal _Color As Color)
    
    Private Sub WriteRTBLog(ByVal Texto As String, ByVal TextColor As Color)
        If Me.InvokeRequired Then
            Dim method As WriteRtbLogDelegate = AddressOf Me.WriteRTBLog
            Me.Invoke(method, Texto, TextColor)
        Else
            If RTB_Log.Lines.Length < 1 Then
                'ultima = 0
                RTB_Log.AppendText("Inicio del LOG - " & Now.ToLongDateString & vbCrLf)
            End If
    
            Dim length As Integer = RTB_Log.Text.Length
    
            Texto = Format(Now.Day, "00").ToString & "/" & Format(Now.Month, "00").ToString & "/" & Now.Year.ToString & " - " & Format(Now.Hour, "00").ToString & ":" & Format(Now.Minute, "00").ToString & ":" & Format(Now.Second, "00").ToString &
                                  " " & Texto
            RTB_Log.AppendText(Texto + vbCrLf)
            RTB_Log.SelectionStart = length
            RTB_Log.SelectionLength = Texto.Length
            RTB_Log.SelectionColor = TextColor
            ' The following expression was wrapped in a checked-expression
            RTB_Log.[Select](RTB_Log.SelectionStart + RTB_Log.SelectionLength, 0)
            RTB_Log.SelectionColor = TextColor
            RTB_Log.SelectionLength = 0
            RTB_Log.SelectionStart = RTB_Log.TextLength
            RTB_Log.ScrollToCaret()
    
            If RTB_Log.TextLength > 1000000.0 Then
                With RTB_Log
                    .SaveFile(Application.StartupPath & "\" & Format(Now.Day, "00").ToString & "-" & Format(Now.Month, "00").ToString & "-" & Now.Year.ToString & " - " &
                              Format(Now.Hour, "00").ToString & Format(Now.Minute, "00").ToString & Format(Now.Second, "00").ToString &
                              ".log", System.Windows.Forms.RichTextBoxStreamType.RichText)
                    .Clear()
                    .Text = "Log guardado en " & Application.StartupPath & Now.ToShortDateString & ".log"
                End With
            End If
        End If
    End Sub
End Class

Private Sub BGW1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BGW1.DoWork
WriteRTBLog("Starting...", Color.Blue)

End Sub

I'm getting an exception:

Operación no válida a través de subprocesos: Se tuvo acceso al control 'RTB_Log' desde un subproceso distinto a aquel en que lo creó.

0

There are 0 best solutions below