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

不羁岁月 提交于 2019-12-10 18:37:11

问题


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


回答1:


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);
}



回答2:


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




回答3:


Doesn't that defeat the purpose of the queue? The queue is supposed to keep the order of the messages, so you have to loop through and keep pulling the first message off.




回答4:


Latest versions of MSMQ also has the following feature:

You can get all messages in a single object such as follows: (Write your own "ReceiveCompleted event" handler)

private static void MyReceiveCompleted(Object source,
        ReceiveCompletedEventArgs asyncResult)
    {
        MessageQueue mq = (MessageQueue)source;
        try
        {
            Message[] mm = mq.GetAllMessages();
            foreach (Message m in mm)
            {
            // do whatever you want
            }
        }
        catch (MessageQueueException me)
        {
            Console.WriteLine(me.Message);
        }
        finally
        {

        }


        return;
    }


来源:https://stackoverflow.com/questions/1228684/how-can-i-get-all-the-available-messages-on-a-msmq-queue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!