使用Windows服务接收MSMQ消息

我正在用C#创建一个Windows服务。

听消息的最佳方法是什么? 我该如何正确编码?

你不听。 您配置MSMQ激活以在邮件到达时激活组件。 该链接包含您需要的所有详细信息,代码和配置。

如前所述,MSMQ Activation可能是最好的方法,如果你可以使用它。 或者,这是我用过的代码:

var ts = new TimeSpan(0, 0, 10); MessageQueue q = GetQueue(); 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 } }