Getting a task queued on a secondary thread to run on the main thread
I have a msg queue that runs on it's own thread that receives msg commands. Does anyone know of a way to launch a task or raise an event on the main thread from the queue thread?
My goal is to receive task on the queue and execute them one at a time on the main thread.
Thank you for you time and kindness.
I could build it that way if required, but the requirements give serveral commands that require reporting back to the GUI, that will involve several controls, and doesn't that mean each control would require an invoke and so on?
I would set this up using events, doing something like this:
Public
Delegate Sub ActionEventHandler()Public Class MessageQueueProcessor
Public Event Action1 As ActionEventHandler
Public Event Action2 As ActionEventHandler
'... Add additional events as necessary
Public Sub StartProcessingEvents()
'...Add code here to interface with MSMQ
End Sub
End Classyou can then singal events from the message queue thread back to the UI thread by firing events.
You can then hookup the events really easily using a withevent variable....
Class MainGUIForm
Private WithEvents queProcessor As MessageQueueProcessor Private Sub HandleAction1() Handles queProcessor.Action1 'determine if we are not on the form's main thread, and if so, marshal
'the call over to that main forms thread.
If (InvokeRequired) Then
'The call to invoke here causes the MessageQueueProcessor thread
'to block untill the code in the "else" block below completes on the UI thread.
'If you do not wish to block the messagequeueprocess, change this to BeginInvoke.
'However, be warned that if you do this it will then become possible for your form
'to process messages out of order.
Invoke(CType(AddressOf HandleAction1, ActionEventHandler))
Else
'Put code to perform action1 here....
End If
End Sub
'Repeat the pattern above for the remaining actions....
End Class
To have the que processor beging processing messages on a seperate thread, you can then put the following code inside your form load event:
new Thread(Addressof queProcessor.StartProcessingEvents()).Start()
-Scott Wisniewski