tags:

views:

358

answers:

4

I'm trying to put a Message back into an MSMQ when an exception is thrown. The following code appears to work but the Message is not put back in the queue?

Message msg = null;
try
{
    MessageQueue MQueue = new MessageQueue(txtMsgQPath.Text);
    msg = MQueue.ReceiveById(txtQItemToRead.Text);
    lblMsgRead.Text = msg.Body.ToString(); // This line throws exception
}
catch (Exception ex)
{
    lblMsgRead.Text = ex.Message;
    if (msg != null)
    {
        MessageQueue MQ = new MessageQueue(txtMsgQPath.Text);
        MQ.Send(msg);
    }
}
A: 

I believe that you're looking to "Peek" at the message. Use: MessageQueue.Peek and if you succeed, then consume the message.

Gavin Miller
That is a good approach but my problem stems from the fact that I will already have "popped" the message and won't be using peek so have to push it onto a retry queue.
Guy
+2  A: 

Is it really your intention to send that message back to the originator? Sending it back to yourself is very dangerous, you'll just bomb again, over and over.

Hans Passant
No that's not really my intention. My intention is to send it to a different queue if it fails. I was just testing the concept on the same queue.
Guy
A: 

I managed to get the code above to work by creating a new queue and pointing the code at the new queue.

I then compared the 2 queues and noticed that the new queue was multicast (the first queue wasn't) and the new queue had a label with the first didn't. Otherwise the queues appeared to be the same.

Guy
+2  A: 

Couple of points: The best way to do this would be using a transaction spanning both queues; that way you'll know you won't lose a message.

The second part of it is to be careful about how the queues are created and how you submit messages to the second queue. In particular, MSMQ sometimes appears to "fail silently" when sending a message (though in reality an error message is recorded elsewhere in the dead letter queues), particularly if the transactional options of the send don't match the transactional nature of the target queue.

tomasr