Recent Posts

Tuesday, July 12, 2011

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on (Multi-Threaded Applicaiton)

I was stuck on this for hours where the event raised from the class wouldn' t write to my textbox in the presentation layer.

I googled but could not find any concrete solution to this but at last after going through various websites i figured out the easier way to solve this.

This article will help users to call the function in the class and raise an event within the class and catch the event in form and display whatever message raised to the text boxes in multi threaded application (
Lets go step by step now:

1. I have a form with command button cmdTest and text box txtAction where I display my messages raised from the class.

Private Sub cmdTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdTest.Click
Dim robot As New RobotProcess_Ama(Nothing)
AddHandler robot.TaskProcessed, AddressOf ActionLog
WorkerThread = New Threading.Thread(AddressOf robot.CheckQueue)
End Sub

Private Sub ActionLog(ByVal FunctName As String, ByVal aMessage As String)
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
txtAction.Text = TimeString & "From: " & FunctName & ":" & aMessage
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = True
End Sub

Here i disabled checkforIllegalcrossThreadcalls and re-enabled them after finishing.

2. Now my class RobotProcess_Ama contains function called checkqueue and raises the message.
Public Sub CheckQueue()
RaiseEvent TaskProcessed("From Class", TimeString & ": Creating log file")
' Threading.Thread.Sleep(200)

Catch ex As Exception
Throw ex
End Try
End Sub

Read more!