Get the Message - MSMQ

Receiving Messages with Events

The technique illustrated in Receiving a Message to receive message has a significant drawback. As long as the process is waiting to receive a message, it can do nothing else. In other words, the message queue holds the process thread hostage. An alternative is to establish an MSMQEvent object that allows your application to respond to incoming messages as events that are raised through this object. The code below shows an example of how to accomplish this. Be aware that there are actually three parts to this code. The first two lines are in the General Declaration portion of the form. They are followed by the Form_Load and event procedures.

Private RequestQ As MSMQQueue
Private WithEvents RequestEvent As MSMQEvent

Private Sub Form_Load()

Dim QI As New MSMQQueueInfo

QI.PathName = "MyServer\QueueName"

Set RequestEvent = New MSMQEvent
RequestQ.EnableNotification RequestEvent

End Sub

Sub RequestEvent_Arrived(ByVal Queue as Object, ByVal Cursor As Long)

Dim InQueue As MSMQQueue
Dim msg As MSMQMessage

Set InQueue = Queue
Set msg = InQueue.Receive(ReceiveTimeOut:=0)
If Not msg is Nothing Then
' Process the message
End If

InQueue.EnableNotification RequestEvent

End Sub

In this example, the EnableNotification method is used to associate an MSMQEvent object with a queue. This causes the Arrived event to be triggered whenever a message is posted to that queue. You should also notice that the EnableNotification method was called again at the bottom of the Arrived procedure. That is because EnableNotification only sets up the event for the next message.

You might also like...


About the author

Bruce Johnson Canada

I am the owner of a small application development consulting company that specialized in the design and implementation of Internet-based applications. While there are others who can make a web ...

Interested in writing for us? Find out more.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Memory is like an orgasm. It's a lot better if you don't have to fake it.” - Seymour Cray