如何从队列中一次抓取一条 MSMQ 消息

How to grab one MSMQ message at a time from the queue

我正在使用控制台应用程序 (C#) 读取 MSMQ 消息。

下面是工作代码。

C#(控制台应用程序)

static void Main(string[] args)
{
     MessageQueue[] myQueueArray = MessageQueue.GetPrivateQueuesByMachine("192.0.0.1");

                    if (myQueueArray != null)
                    {                    
                        foreach (MessageQueue mq in myQueueArray)
                        {
                            if (mq.QueueName.Contains("myqueue"))
                            {
                                myQueue = mq;
                                break;
                            }
                        }

                        if (myQueue != null)
                        {

                            Message[] messageList = myQueue.GetAllMessages();
                            if (messageList != null)
                            {                           
                                foreach (Message msg in messageList)
                                {    
                                 //doing some operation with the message
                                }    
                            }    
                        }
                     }
                 }

以上代码运行良好。

但我想一条一条地阅读 MSMQ 消息我如何一次从队列中抓取一条消息?

您可以使用 MessageQueue.Receive 一次出列单个消息,请参阅此 MSDN article. You can also use BeginReceive and ReceiveCompleted event to get the notification, see this MSDN article

编辑

MSDN link 具有非常简单的示例代码,可帮助 OP 从 MSMQ 中取出消息(通过注释指出)