How can I remove messages from a queue?

一笑奈何 提交于 2019-11-30 03:56:59

问题


I have messages that get stuck in queue and I am looking for a way to programmatically remove them.

Is there a way to remove messages from a queue if it has been sitting for more than x days? I can connect and delete a queue like this, but not sure how to remove individual messages.

MessageQueue queue = new MessageQueue(@".\private$\SomeTestName");
//queue.Purge(); //deletes the entire queue
try
{
    // Peek and format the message. 
    Message m = myQueue.Peek();

   // Display message information.
   Console.WriteLine("Sent time {0}", m.SentTime);
   Console.WriteLine("Arrived time {0}", m.ArrivedTime);
}

回答1:


There is no API available to do this. But you can use

  • GetMessageEnumerator2() and
  • RemoveCurrent()

A benefit of using enumeration is that if a queue has many messages, reading all of them may result in OutOfMemoryException. With enumerator you only read 1 message at a time, and memory allocated for it can be reused.

Another trick to increase performance is to specify which properties to read, so that if message body is large and you aren't interested in the content, you can disable reading it.

var enumerator = _queue.GetMessageEnumerator2();  // get enumerator
var staleDate = DateTime.UtcNow.AddDays(-3);      // take 3 days from UTC now    
var filter = new MessagePropertyFilter();         // configure props to read
filter.ClearAll();                                // don't read any property
filter.ArrivedTime = true;                        // enable arrived time
_queue.MessageReadPropertyFilter = filter;        // apply filter

while (enumerator.MoveNext())    
     if(enumerator.Current.ArrivedTime.Date >= staleDate)
         enumerator.RemoveCurrent();



回答2:


I think you can do something like this:

MessageQueue queue = new MessageQueue(@".\private$\SomeTestName");
var messages = queue.GetAllMessages();
var messagesToDelete = messages.Where(m => m.ArrivedTime < DateTime.Now.AddDays(-1)).ToList();
messagesToDelete.ForEach(m=>queue.ReceiveById(m.Id));

Obviously, you'll have to modify the date stuff to correspond with your scenario.




回答3:


You could also use the ReceiveById method to remove the messages from the queue.

Check this link out: https://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.receivebyid%28v=vs.110%29.aspx




回答4:


Call GetAllMessages and add a check to find your message and do a delete operation on that message. Sample code,

    Message[] messages = msgQueue.GetAllMessages();
    foreach (Message msg in messages){
         doSomething();
    }


来源:https://stackoverflow.com/questions/23227194/how-can-i-remove-messages-from-a-queue

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