Reputation: 3936
I have a message queue where i add some emails. I want to extract all emails, examine the date when they were added and their priority and send only one of them. I read messages like this:
private IList<Email> GetEmailsFromQueue(MessageQueue queue)
{
queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(Email) });
IList<Email> emails = new List<Email>();
Cursor cursor = queue.CreateCursor();
Message m = PeekWithoutTimeout(queue, cursor, PeekAction.Current);
if (m != null)
{
emails.Add((Email)m.Body);
while ((m = PeekWithoutTimeout(queue, cursor, PeekAction.Next)) != null)
{
emails.Add((Email)m.Body);
}
}
return emails;
}
private Message PeekWithoutTimeout(MessageQueue q, Cursor cursor, PeekAction action)
{
Message msgFromQueue = null;
try
{
msgFromQueue = q.Peek(new TimeSpan(1), cursor, action);
}
catch(MessageQueueException ex)
{
if (!ex.Message.ToLower().Contains("timeout"))
{
throw;
}
}
return msgFromQueue;
}
Receive method will remove the message from the queue. Is there any way to read and remove only some messages?
LE: One solution i mighty think of is to add an id to each message, and use ReceiveById
Any other tips?
Upvotes: 3
Views: 2902
Reputation: 18349
Is there any way to read and remove only some messages?
I've never used MSMQ (well not in anger anyways) but I think you should be able to combine both the Peek
and ReceiveById
methods.
So you would continue to Peek
at the queue to see what messages are available and then once you have decided to remove a message make use of the ReceiveById
, to process/remove from the queue.
Aside from this perhaps the other option would be to make use of 2 queues. The first would be for all inbound messages and the second would be used to add back messages you want to keep.
So going back to your example (assuming I understand what you're trying to achieve)
Upvotes: 4