msmqnetmsmqbindingmsmq-wcf

How to receive MSMQ Messages


Whats the best way to receive MSMQ messages.

I used the following code, but after receiving MSMQ messages not getting removed in Queue

var msgEnumerator = myQueue.GetMessageEnumerator2();
            var messages = new List<System.Messaging.Message>();
            while (msgEnumerator.MoveNext(new TimeSpan(0, 0, 1)))
            {
                var msg = myQueue.ReceiveById(msgEnumerator.Current.Id, new TimeSpan(0, 0, 1));
                messages.Add(msg);
                for (int i = 0; i < messages.Capacity; i++)
                {
                    String DataMessages = messages[i].ToString();
                }

But i cant receive messages.

How to receive those messages.


Solution

  • I would use asynchronous MessageQueue.BeginPeek to start listening on the queue:

    queue.BeginPeek();
    

    Then register a handler with the MessageQueue.PeekCompleted event:

    queue.PeekCompleted += new PeekCompletedEventHandler(MessageHasBeenReceived);
    

    Then in your handler use MessageQueue.EndPeek to access the message. Remember to call BeginPeek again.

    private void MessageHasBeenReceived(object sender, PeekCompletedEventArgs e)
    {
        // Get message
        var msg = queue.EndPeek(e.AsyncResult);
    
        // Do message processing here
        ....
    
        // Remove message from queue
        queue.ReceiveById(msg.Id);
    
        // Listen for more messages
        queue.BeginPeek();
    }
    

    See here for MSDN example.