Reading Messages Synchronously

When reading messages synchronously, all calls are blocked until the next message is available or timeout occurs.

To read a message synchronously
  1. Open the queue with receive or peek access.
    Set qDest = qinfoDest.Open(MQ_RECEIVE_ACCESS, MQ_DENY_NONE)
    
  2. Call Receive or Peek to read each message in the queue. The example below uses Receive to remove each message in the queue. (Using Peek in the code below create an infinite loop.)
    Do While True
       Set msgDest = qDest.Receive(ReceiveTimeout:=1000)
       If msgDest Is Nothing Then Exit Do
       MsgBox msgDest.Label + " is removed from the queue."
    Loop
    

Example

This example reads all messages in a queue, removing each message as it is read. An error handler is added to trap any errors generated as a result of the Receive call.

To try this example using Microsoft® Visual Basic® (version 5.0), paste the code into the Code window of a form, and then run the example and click the form.

Option Explicit
Dim qinfoDest As MSMQQueueInfo
Dim qDest As MSMQQueue
Dim msgDest As MSMQMessage

Private Sub Form_Click()
   
   '**********************
   ' Removes all messages
   ' in the queue.
   '**********************
   
   Set qDest = qinfoDest.Open(MQ_RECEIVE_ACCESS, MQ_DENY_NONE)
  
   On Error GoTo Handler
   
   Do While True
      Set msgDest = qDest.Receive(ReceiveTimeout:=1000)
      If msgDest Is Nothing Then Exit Do
      MsgBox msgDest.Label + " is removed from the queue."
   Loop

   Exit Sub

   '***************
   ' Error Handler
   '***************
   
Handler:
   If (Err = MQ_ERROR_IO_TIMEOUT) Then
      MsgBox "All messages are removed from the queue."
      Exit Sub
   Else
      MsgBox "Unexpected error!"
   End If

End Sub
 

© 1997 by Microsoft Corporation. All rights reserved.