I've ran into a bit of an issue today that involves MSMQ. I had an Asp.Net webservice who also ran a job (basically a new Thread that loops forever) that was doing a Receive on a MessageQueue object and writing the Message it got (or rather the body of the message) to a database. The business of the job was such that calling Receive, which is synchronous (blocking), was ok.
It all worked fine, except that whenever I changed something in the web.config file and the AppDomain would get recycled, the next
message posted to the message queue would get read from it, but it would never get written to the database. Since no one else was reading from the queue I thought it was an issue with my code. So I did some logging and debugging and in the end came to the conclusion that after
the AppDomain recycled, the first
message posted to the queue would get read by somebody, but not the code in my app. The second
(next) message posted to the queue, plus all the next other messages posted from then on would get read fine and written to the database. Huh?!
Unfortunately, since it's my first experience with MSMQ, I don't have a definitive answer for the problem. Maybe some of you could help. My theory is that somehow... somehow... since the Receive call is synchronous, when the AppDomain recycles, there's still something left somewhere (outside of the app or even the .NET framework, I'm thinking about an OS thing) that is waiting to get the first message to be posted to the queue. So when that message gets posted, the "something
" gets it, instead of my app. As I said, it's just a theory, so if you know anything about this, please share.
Anyway, I did find a workaround: it involves using the BeginReceive() method and subscribing to the ReceiveComplete event of the MessageQueue. This approach worked, resulting in the event handler for the ReceiveComplete event being called even for the first message posted to the queue just after a AppDomain recycle. The only thing needed then is to just BeginReceive() again on the queue, after getting the message, to subscribe for the next one.