Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i get all the available messages on a MSMQ Queue

Tags:

c#

.net

msmq

Whats the best way to get all the messages currently on a queue to process?

We have a queue with a large number of very small messages, what I would like to do is read all the current messages off and then send them through a thread pool for processing.

I can't seem to find any good resource which will show me how i can create a simple method to return an IEnnumerable for example

Thanks

like image 417
Kev Hunter Avatar asked Aug 04 '09 16:08

Kev Hunter


People also ask

Where are MSMQ files stored?

Default is c:\windows\system32\msmq\.

What happens when message queue is full?

Multiple tasks can send messages to a message queue; a sending task can be blocked when the target message queue is full. A message queue can also have multiple tasks receiving messages from it; a receiving task can be blocked when the queue is empty.

Is MSMQ obsolete?

As a Windows component, MSMQ is technically “supported” as long as it's carried by a supported version of Windows. Since it exists in Windows 10 and Windows Server 2019, MSMQ will continue to live on until at least 2029—and much longer assuming it isn't removed from future versions of Windows.


2 Answers

Although I agree with Nick that the queue's purpose is more for FIFO style processing, and ArsenMkrt's solution will work, another option involves using a MessageEnumerator and piling the messages into your IEnumerable.

var msgEnumerator = queue.GetMessageEnumerator2();
var messages = new List<System.Messaging.Message>();
while (msgEnumerator.MoveNext(new TimeSpan(0, 0, 1)))
{
    var msg = queue.ReceiveById(msgEnumerator.Current.Id, new TimeSpan(0, 0, 1));
    messages.Add(msg);
}
like image 148
AJ. Avatar answered Sep 30 '22 19:09

AJ.


For simple stuff...

public void DoIt()
    {

        bool continueToSeekForMessages = true;

        while (continueToSeekForMessages)
        {
            try
            {
                var messageQueue = new System.Messaging.MessageQueue(@"FormatName:Direct=OS:MyComputerNameHere\Private$\MyPrivateQueueNameHere");
                var message = messageQueue.Receive(new TimeSpan(0, 0, 3));
                message.Formatter = new System.Messaging.XmlMessageFormatter(new String[] { "System.String,mscorlib" });
                var messageBody = message.Body;

            }
            catch (Exception ex)
            {
                continueToSeekForMessages = false;
            }
        }
    }

.

Also, could use peek instead of taking the message off the queue.

Also, could use GetMessageEnumerator2

like image 27
barrypicker Avatar answered Sep 30 '22 18:09

barrypicker