如何在Windows服务中处理消息队列失败?

时间:2017-02-15 08:02:17

标签: c# windows-services msmq

我有一个Windows服务,它通常从另一台服务器的msmq接收消息。

它大部分时间都可以工作,但每月一次,它会低于错误:

队列不存在或您没有足够的权限来执行操作。

Exception Message: The queue does not exist or you do not have sufficient permissions to perform the operation.
 Stack Trace:    at System.Messaging.MessageQueue.ResolveFormatNameFromQueuePath(String queuePath, Boolean throwException)
   at System.Messaging.MessageQueue.get_FormatName()

或者有时候:

Exception Message: 
 Stack Trace:    at System.Messaging.MessageQueue.MQCacheableInfo.get_ReadHandle()
   at System.Messaging.MessageQueue.StaleSafeReceiveMessage(UInt32 timeout, Int32 action, MQPROPS properties, NativeOverlapped* overlapped, ReceiveCallback receiveCallback, CursorHandle cursorHandle, IntPtr transaction)

因此它是随机的,唯一的解决方案是手动重启服务。

对于消息队列异常,我们抛出异常,这就是为什么只有运行应用程序的解决方案是手动重启服务。

我想让应用程序重试5次,如果连续失败则执行重启等操作。

我已经尝试了下面的代码,但是当它停止时,它显然不会回到下面的代码再次启动它,因为服务本身试图重新启动。

catch (MessageQueueException e)
                        {
                            if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                            {
                                // Very unusual
                                LogWrapper.WriteErrorLog(e, "MessageQueueException occuring for the following machine: " + queue.MachineName + " and the following queue: " + queue.QueueName, false, DateTime.Now);

                                // Restart service if it fails for more than 5 times
                                if (maxTries == 0)
                                {
                                    var service = new System.ServiceProcess.ServiceController(serviceName);
                                    service.Stop();
                                    //service.WaitForStatus(ServiceControllerStatus.Stopped);

                                    LogWrapper.WriteErrorLog(e, "Restarting service as it reached maximum retry count for exception: " + e.Message, false, DateTime.Now);
                                    service.Start();
                                    service.WaitForStatus(ServiceControllerStatus.Running);
                                    //Environment.Exit(1);
                                }

                                maxTries--;
                                //throw;
                            }

在这种情况下,最佳解决方案应该是什么?

0 个答案:

没有答案