Introduction
My first article on Message Queues: "Using Message Queue in .NET Framework 2.0 " would help you to send and receive messages from a Message Queue server of the Windows Operating System. Now there is a thing here you might not know when there are messages in the Message Queue server.
You can't keep calling a simple receive command or peek command to check whether there are any messages available in the queue. If you do so, you will find that the application hangs until it finds any messages in the queue. So to solve that problem, we can use this message queue asynchronously. For that, we need to change the approach of receiving messages.
We will use the BeginPeek
to start peeking the message queue for any new message arrival, and BeginRecieve
to start receiving any new messages from the queue. This method works on other threads, so it means the work of checking and receiving messages is done in the background.
When we use:
- the
BeginPeek
method, an event fires up whe ever a message is found that is
PeekCompleted
, which occurs when a message is read without being removed from the queue. This is a result of an asynchronous operation.
BeginRecieve
method a event fires up when ever a message is recieved that is
ReceiveCompleted
, which occurs when a message has been removed from the queue. This event is raised by an asynchronous operation.
Using the Code
BeginPeek Method
myQueue.BeginPeek()
Once the BeginPeek
method is called, a new thread is started for checking for any messages in the queue. Now we need to handle the PeekCompleted
event
Private Sub CheckQueueu(ByVal sender As System.Object, _
ByVal e As System.Messaging.PeekCompletedEventArgs) _
Handles myQueue.PeekCompleted
If e.Message.Label = "Example" Then
msgQueue.Enqueue(e.Message)
myQueue.Receive()
myQueue.Refresh
myQueue.BeginPeek()
End If
End Sub
BeginReceive Method
myQueue.BeginReceive()
Once the BeginReceive
method is called, a new thread is started for checking for any messages in the queue. Now we need to handle the ReceiveCompleted
event.
Private Sub RecQueueu(ByVal sender As System.Object, _
ByVal e As System.Messaging.ReceiveCompletedEventArgs) _
Handles myQueue.ReceiveCompleted
msgQueue.Enqueue(e.Message)
myQueue.Receive()
myQueue.Refresh
myQueue.BeginReceive()
End If
End Sub
The code above came through research and a combination of articles and examples. In my next article, I will try to explain more on both the BeginPeek
and BeginReceive
methods, also passing some parameters to them.
Hoping this might help you in some way.