Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MSMQ - beginreceive 1

Status
Not open for further replies.

haddaway

Programmer
Jul 6, 2005
172
0
0
SE
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?
 
When you call BeginReceive, if there's nothing to be read, it will block until some other thread/process writes to the queue.

If you're reading more than one message (like you're writing a server app that programs send messages to over the day), you should add another call to BeginReceive at the end of your receive handler event to kick off the process again.

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top