是否有可能使用MSMQ MessageQueue.Peek丢失消息并超时?

Mic*_*rio 5 c# windows-services msmq

我目前遇到丢失消息的问题.这个错误很少发生,但经常发生,这很烦人.以下是该问题的背景:

  • 我已经打开了goldmine_service_queue上的消息日志,这是Windows 2003服务器上的MSMQ.
  • 我可以证明消息正在插入goldmine_service_queue,因为消息出现在消息日志中.此信息提供有关消息何时消失的计时信息.
  • 日志记录功能使用http://logging.apache.org/log4net/index.html
  • 日志不显示错误.
  • worker函数(如下所示)在Windows服务的一个线程中执行.它负责从队列中查看消息(工作项)并处理它们.
  • 从日志中,我强烈怀疑我的问题可能与MessageQueue.Peek和超时行为有关.

超时和消息接收是否可能同时发生?有没有更好的方法来处理服务停止检查以帮助避免此错误?

        private void workerFunction()
    {

        logger.Info("Connecting to queue: " + Settings.Default.goldmine_service_queue);
        MessageQueue q = new MessageQueue(Settings.Default.goldmine_service_queue);
        q.Formatter = new ActiveXMessageFormatter();

        while (serviceStarted)
        {

            Message currentMessage = null;

            try
            {
                currentMessage = q.Peek(new TimeSpan(0,0,30));
            }
            catch (System.Messaging.MessageQueueException mqEx)
            {
                if (mqEx.ToString().Contains("Timeout for the requested operation has expired"))
                {
                    logger.Info("Check for service stop request");
                }
                else
                {
                    logger.Error("Exception while peeking into MSMQ: " + mqEx.ToString());
                }
            }
            catch (Exception e)
            {
                logger.Error("Exception while peeking into MSMQ: " + e.ToString());
            }

            if (currentMessage != null)
            {

                logger.Info(currentMessage.Body.ToString());
                try
                {
                    ProcessMessage(currentMessage);
                }
                catch (Exception processMessageException)
                {
                    logger.Error("Error in process message: " + processMessageException.ToString());
                }

                //Remove message from queue.
                logger.Info("Message removed from queue.");
                q.Receive();
                //logPerformance(ref transCount, ref startTime);
            }


        }//end while

        Thread.CurrentThread.Abort();

    }
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 5

我不认为根据快速审查会遗漏任何消息,但你的工作方式非常奇怪,有很多竞争条件.

为什么不直接接收消息并将其传递给ProcessMessage(如果ProcessMessage失败,则无论如何都要执行读取).如果需要处理多个接收器,则在MSMQ事务中执行接收,以使消息对其他接收器不可用,但在提交事务之前不会从队列中删除.

此外,不是轮询队列,为什么不进行异步接收并让线程池处理完成(必须调用的地方EndReceive).这样可以节省绑定线程,并且您不需要关闭特殊情况服务(关闭消息队列然后调用MessageQueue.ClearConnectionCache();).

此外,中止线程是一种非常糟糕的退出方式,只需从线程的启动函数返回即可.