Cross Thread is not Valid:
Hi I am trying to call a Sub from another thread but it always throwing me an error: Cross Thread is not valid.
here is the Sub I am calling from other thread.
vb Code:
Private Delegate Sub AppendToLogInvoker(ByVal strText As Object, ByVal color As Integer)
vb Code:
Private Sub WriteToLog(ByVal strText As Object, ByVal color As Integer) 'As Object
If Me.Log.InvokeRequired Then
Me.Log.Invoke(New AppendToLogInvoker(AddressOf WriteToLog), strText, color)
End If
Me.Log.SelectionStart = Len(Log.Text)
Me.Log.SelectionColor = System.Drawing.ColorTranslator.FromOle(color)
Me.Log.SelectedText = strText
Me.Log.SelectionStart = Len(Log.Text)
Me.Log.SelectedText = vbCrLf
End Sub
I am calling that on other thread with this:
vb Code:
WriteToLog(" [" & System.DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") & "] " _
& "ERROR: Sending failed! " _
, System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red))
I am getting stock at this point
vb Code:
Me.Log.SelectionStart = Len(Log.Text)
Re: Cross Thread is not Valid:
The problem is that you're still accessing Me.Log on the secondary thread. When you call the WriteToLog method you have an If statement that calls Invoke if required, but then you proceed to access Me.Log OUTSIDE the If block, so that code is executed regardless of the thread. You should have an If...Else block. Follow the CodeBank link in my signature and check out my submission on Accessing Controls From Worker Threads for more information.
Re: Cross Thread is not Valid:
@JM
This is my guide when coding that..
http://www.vbforums.com/showthread.php?t=498387
I revise my code.
vb Code:
Private Sub WriteToLog(ByVal strText As Object, ByVal color As Integer) 'As Object
If Me.Log.InvokeRequired Then
Me.Log.Invoke(New AppendToLogInvoker(AddressOf WriteToLog), strText, color)
Else
Me.Log.SelectionStart = Len(Log.Text)
Me.Log.SelectionColor = System.Drawing.ColorTranslator.FromOle(color)
Me.Log.SelectedText = strText
Me.Log.SelectionStart = Len(Log.Text)
Me.Log.SelectedText = vbCrLf
End If
End Sub
It works. But is that correct coding?
Re: Cross Thread is not Valid:
That is exactly correct. When you call the method for the first time, on the secondary thread, InvokeRequired is True so execution enters the If block and the only code executed is the Invoke call. When the method is invoked for the second time, on the UI thread, InvokeRequired is False and execution enters the Else block and the only code executed is the UI access.