Search code examples
c#.netmessage-queuedispose

Why won't my MessageQueue close properly?


How can I stop a synchronous or asynchronous Receive from a MessageQueue in C#?

I find that if I haven't received any messages from the queue since I opened it, I can simply Close / Dispose the queue, and the Receive or EndReceive method will except, which is fine. However, if I've already successfully received a message from the queue, I can close and dispose the queue, but the pending or asynchronous receive will carry on regardless!

I've read elsewhere and found some suggestion that I should get EnableConnectionCache to false to ensure the message queue is closed when I ask, but it still seems to be ignore me regardless.


Solution

  • As binarycoder suggested, I have found that this is just a consequence of non-transactional queues. At least as far as MSMQ goes. A peek > receive pattern will solve the problem, but only if there is one reader. Otherwise, if you have the same issue you'll have to use transactional queues.