Windows服务不会连续从msmq中选择邮件

时间:2018-04-04 19:45:23

标签: c# service msmq

Windows服务未从MSMQ中选择邮件。每当有消息时,我都必须去服务站停止并开始我的服务,然后它才会选择。

这是代码。请让我知道必须做些什么来使服务持续观察消息并在有消息时立即选择。

 public partial class Service1 : ServiceBase
    {    
        private const string MqName = @".\private$\RequestQueue";
        private static MessageQueue _mq;        

private static MessageQueue mq
    {
        get
        {
            if (_mq == null)
            {
                if (!MessageQueue.Exists(MqName))
                    MessageQueue.Create(MqName);
                _mq = new MessageQueue(MqName, QueueAccessMode.ReceiveAndAdmin);
                _mq.Formatter = new BinaryMessageFormatter();
            }
            return _mq;
        }
    }  
 public Service1()
    {
        InitializeComponent();
   mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
    } 

private void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {

            MessageQueue cmq = (MessageQueue)sender;
            try
            {              
                Message msg = cmq.EndReceive(e.AsyncResult);              
            }
            catch
            {
            }
            cmq.Refresh();
            cmq.BeginReceive();
        }


        protected override void OnStart(string[] args)
        {
            if (mq != null)
                mq.BeginReceive();
        }
    private void MsMq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
    {
        var msMq = (MessageQueue)sender;
        var msg = msMq.EndReceive(e.AsyncResult);
        msMq.BeginReceive();          
    }
    protected override void OnStop()
    {          
        if (mq != null)
            mq.Close();
        return;

    }
}

0 个答案:

没有答案