I have the following example:
Private Sub StartListening()
Dim myReceiveQueue As MessageQueue
Try
' open the receive queue
myReceiveQueue = New _
MessageQueue(".\private$\myqueue")
' set the receive queue formatter
myReceiveQueue.Formatter = New XmlMessageFormatter( _
New Type() {GetType(System.String)})
' add a handler for the ReceiveCompleted event and
' call BeginReceive
AddHandler myReceiveQueue.ReceiveCompleted, _
AddressOf MSMQ_ReceiveCompleted
myReceiveQueue.BeginReceive()
Catch ex As Exception
MessageBox.Show("Generic Exception was thrown: " _
& ex.Source & ": " & ex.Message)
End Try
End Sub
Public Sub MSMQ_ReceiveCompleted( _
ByVal p_source As Object, _
ByVal p_objAsyncResult As ReceiveCompletedEventArgs)
Dim myMessage As Message
Dim myMessageQueue As MessageQueue
' cast the source parm to a MessageQueue object
myMessageQueue = CType(p_source, MessageQueue)
' calling EndReceive will return the message that was received
myMessage = myMessageQueue.EndReceive( _
p_objAsyncResult.AsyncResult)
' do something useful with the message
MessageBox.Show("received")
End Sub
This sample works well but I wonder one thing. I want the listener to be listening all the time on that queue. What is the best approach? Starting a BeginReceive once a message is read? Or, how do I "loop" it the best way?
Private Sub StartListening()
Dim myReceiveQueue As MessageQueue
Try
' open the receive queue
myReceiveQueue = New _
MessageQueue(".\private$\myqueue")
' set the receive queue formatter
myReceiveQueue.Formatter = New XmlMessageFormatter( _
New Type() {GetType(System.String)})
' add a handler for the ReceiveCompleted event and
' call BeginReceive
AddHandler myReceiveQueue.ReceiveCompleted, _
AddressOf MSMQ_ReceiveCompleted
myReceiveQueue.BeginReceive()
Catch ex As Exception
MessageBox.Show("Generic Exception was thrown: " _
& ex.Source & ": " & ex.Message)
End Try
End Sub
Public Sub MSMQ_ReceiveCompleted( _
ByVal p_source As Object, _
ByVal p_objAsyncResult As ReceiveCompletedEventArgs)
Dim myMessage As Message
Dim myMessageQueue As MessageQueue
' cast the source parm to a MessageQueue object
myMessageQueue = CType(p_source, MessageQueue)
' calling EndReceive will return the message that was received
myMessage = myMessageQueue.EndReceive( _
p_objAsyncResult.AsyncResult)
' do something useful with the message
MessageBox.Show("received")
End Sub
This sample works well but I wonder one thing. I want the listener to be listening all the time on that queue. What is the best approach? Starting a BeginReceive once a message is read? Or, how do I "loop" it the best way?