问题
I'm creating a Windows Service in C#.
What is the best way to listen for messages?? How do I code this properly??
回答1:
You don't listen. You configure MSMQ Activation to activate your component when messages arrive. The link has all the details you need, code and configuration.
回答2:
As previously stated, MSMQ Activation is probably the best way, if you can use that. Alternatively, here is code that I've used:
var ts = new TimeSpan(0, 0, 10);
MessageQueue q = GetQueue<T>();
while (true)
{
try
{
Message msg = q.Receive(ts);
var t = (T)msg.Body;
HandleMessage(t);
}
catch (MessageQueueException e)
{
// Test to see if this was just a timeout.
// If it was, just continue, there were no msgs waiting
// If it wasn't, something horrible may have happened
}
}
来源:https://stackoverflow.com/questions/1521841/receiving-msmq-messages-with-windows-service