Reputation: 1451
i'm reading messages from MessageQueue using PeekCompleted, i do my process here and if everything go right, I need to remove it from the Queue! currenty i am using MyMessageQueue.Receive() and it works, but is this a reliable way of making sure each message will be processed right?
MessageQueue MyMessageQueue;
public Form1()
{
InitializeComponent();
MyMessageQueue = new MessageQueue(@".\private$\Dms");
MyMessageQueue.PeekCompleted += new PeekCompletedEventHandler(MessageQueue_PeekCompleted);
MyMessageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
MyMessageQueue.BeginPeek();
}
void MessageQueue_PeekCompleted(object sender, PeekCompletedEventArgs e)
{
try
{
Debug.WriteLine("ToProcess:" + e.Message.Body);
//Long process that maybe fail
MyMessageQueue.Receive();
}
finally
{
MyMessageQueue.BeginPeek();
}
}
Upvotes: 3
Views: 2821
Reputation: 6186
This will work provided you're always only got one receiver of the queue - another process could peek and receive that message inbetween the BeginPeek and Receive methods. This will also be the case with the ReceiveById suggestion above.
If you only ever want one receiver, you can open the queue with the DenySharedReceive flag to enforce this.
Upvotes: 1
Reputation: 8131
Receive() receives the first message in the queue, removing it from the queue. What you need is MessageQueue.ReceiveById Method
MyMessageQueue.ReceiveById(e.Message.Id);
Secondly, I think, you always need to call MessageQueue.EndPeek Method
Message m = MyMessageQueue.EndPeek(e.AsyncResult);
Upvotes: 4
Reputation: 20556
I always try to use the same BeginPeek() method because this way, I can let other job can be processed even when there is delay in message arrival and when peek returns after completion, you can pick the message. I think above you just showed the code snippet as example, because you may need to write own class/methods to get it done with new messages checks, along with full try and catch blocks in your client app.
Upvotes: 0