我有一个消息队列,我在其中添加了一些电子邮件。 我想提取所有电子邮件,检查添加日期和优先级,然后只发送其中一封。 我读过这样的消息:
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 方法将从队列中删除消息。 有什么方法可以只读取和删除部分消息吗?
LE:我想到的一个解决方案是为每条消息添加一个 id,并使用 ReceiveById
还有什么建议吗?
最佳答案
Is there any way to read and remove only some messages?
我从来没有使用过 MSMQ(反正不是生气),但我认为您应该能够结合使用 Peek
和 ReceiveById
方法。
因此,您将继续Peek
队列以查看有哪些消息可用,然后一旦您决定删除消息,请使用ReceiveById
进行处理/从队列中删除。
除此之外,另一个选择可能是使用 2 个队列。第一个用于所有入站消息,第二个用于添加您要保留的消息。
回到你的例子(假设我理解你想要达到的目标)
- 第一个是针对入站电子邮件,您按照所述处理提取所有电子邮件,检查添加日期及其优先级
- 第二个用于您的出站电子邮件,即一旦您收到要发送的电子邮件,将其推送到出站队列
关于c# - 仅处理消息队列中的部分消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11882671/