Windows服务仅在服务启动时首次接收MSMQ消息

时间:2018-03-19 18:24:17

标签: c# windows-services msmq

我第一次使用Windows服务和MSMQ。我正在尝试从队列中读取消息。当我启动我的Windows服务时,我只收到第一条消息而下一条消息无法读取,服务仍在运行。如果我重新启动服务它正在从队列中读取第一条消息。请让我知道如何解决这个问题。

这是我开始服务时的代码:

<div class="bar">
  <button id='tab1' class="underline" onclick='switchTab(2)'>Tab 1</button>
  <button id='tab2' onclick='switchTab(1)'>Tab 2</button>
</div>

2 个答案:

答案 0 :(得分:0)

只是一个猜测,但我认为你不应该关闭队列:

//keep your queue object in the service scope
//you might need more 
MessageQueue msMq = null;
protected override void OnStart(string[] args)
{   
    JobModel j = new JobModel();
    msMq = new MessageQueue(queueRequestName);
    try
    {            
        if (msMq != null)
        {                    
            msMq.Formatter = new XmlMessageFormatter(new Type[] { typeof(JobModel) });
            var message = (JobModel)msMq.BeginReceive(); 
        }
    }

    catch (MessageQueueException ee)
    {
        Console.Write(ee.ToString());
    }
    catch (Exception eee)
    {
        Console.Write(eee.ToString());
    }
}

//close when you stop
protected override OnStop() //signature might be differnt
{
    msMq.Close();
}

答案 1 :(得分:0)

您是否尝试过添加事件处理程序并将其附加到ReceiveCompleted事件,如MessageQueue.BeginReceive所示?

protected override void OnStart(string[] args)
{

    MessageQueue msMq = null;
    JobModel j = new JobModel();
    msMq = new MessageQueue(queueRequestName);
    msMq.ReceiveCompleted += ReceiveCompletedEventHandler(MyMsMqEventHandler)
    try
    {            
        if (msMq != null)
        {                    
            msMq.Formatter = new XmlMessageFormatter(new Type[] { typeof(JobModel) });
            var message = (JobModel)msMq.BeginReceive();        

        }
    }

    catch (MessageQueueException ee)
    {
        Console.Write(ee.ToString());
    }
    catch (Exception eee)
    {
        Console.Write(eee.ToString());
    }
}

public static void MyMsMqEventHandler(object src, ReceiveCompletedEventHandler handler)
{
     var msMq = (MessageQueue)src;
     var msg = msMq.EndReceive(handler.AsyncResult);
     Console.WriteLine((string)msMq.Body);
     msMq.BeginReceive();
}