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.
Learningner
source share