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 (VB.net)
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)
WorkerThread.Start()
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()
Try
RaiseEvent TaskProcessed("From Class", TimeString & ": Creating log file")
' Threading.Thread.Sleep(200)

Catch ex As Exception
Throw ex
End Try
End Sub

Related Posts by Categories




1 comment:

Adams Kevin said...

I ADAMS KEVIN, a representative Aiico Insurance plc, we trust and respect for individual differences in day out a loan. We will provide 2% of the loan's interest rate. If you are interested in this business contact us by e-mail: (adams.credi@gmail.com) now transfer their loan documents issued properly. Do you need a loan to set up business or school if you are very welcome to Aiico Insurance plc. You can also contact us by e-mail: (adams.credi@gmail.com). We first week can request a balance transfer.

DO YOU NEED LOAN FOR PERSONAL BUSINESS? IF YOU CONTACT YOUR EMAIL ABOVE TO PROCEED WITH YOUR LOAN TRANSFER IMMEDIATELY OK.

Post a Comment