How to remove a message from the message queue (only if it is well formatted)?

I want to transfer a message from one queue and send it to the database. I want to do this only if it is in a specific format.

If I use the Receive method directly, and there is some exception when accessing the Body message, I lose the message because the Receive MessageQueue method removes the message from the queue.

To avoid losing the message, now I first Peek message, and if it is well formatted, I use the Receive method to remove it from the queue in order to send it to the database.

The code I wrote is as follows:

  Message msg = _queue.Peek(new TimeSpan(0, 0, LoggingService.Configuration.ReceiveTimeout)); // LogMessage is my own class which is adding some more stuff to original message from MessageQueue LogMessage message = null; if (msg != null) { if (!(msg.Formatter is BinaryMessageFormatter)) msg.Formatter = new BinaryMessageFormatter(); message = LogMessage.GetLogMessageFromFormattedString((string) msg.Body); // Use Receive method to remove the message from queue. This line will we executed only if the above line does not // throw any exception ie if msg.Body does not have any problem Message wellFormattedMsg = _queue.ReceiveById(msg.Id); SendMessageToDatabase(message); } 

Is this logic correct for using Peek and then getting? Or is there another better way f to achieve the same thing? Please note that I do not want to receive all messages at a time. MessageQueue is not transactional.

+1
c # msmq
source share
2 answers

This is the same approach that I take when manually deleting a message one at a time, and I did not encounter any problems.

The only thing you do not have to deal with is to process a message in a queue that does not have the required format. Your intention to leave him in line? If so, you may end up in a very large queue and have all sorts of problems finding messages in the queue that have not yet been expected. Apparently, it makes sense to also disable messages that do not have the required format, and store them in another place if they cannot be deleted.

+2
source share

"If I use the Receive method directly and some exception occurs when accessing the Message Body, I lose the message because the Receive MessageQueue method removes the message from the queue."

You must use transactional requests so that the message is returned to the queue when / if the transaction is aborted.

Greetings
John Broadwell

+1
source share

All Articles