Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove messages from a queue?

Tags:

c#

msmq

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);
}
like image 490
John Smith Avatar asked Apr 22 '14 18:04

John Smith


2 Answers

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

  • GetMessageEnumerator2() and
  • RemoveCurrent(), which also moves the cursor

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 the 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

// untested code here, edits are welcome
while (enumerator.Current != null)    
     if(enumerator.Current.ArrivedTime.Date >= staleDate)
         enumerator.RemoveCurrent();
     else
         enumerator.MoveNext();
like image 156
oleksii Avatar answered Sep 19 '22 07:09

oleksii


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.

like image 43
tobyb Avatar answered Sep 19 '22 07:09

tobyb