コード例 #1
0
        private void MSMQReceiveThread()
        {
            try
            {
                while (true)
                {
                    Thread.CurrentThread.Join(1000);
                    ServiceController serviceController1 = ServiceManager.GetService(ConstValue.MSMQServiceName);

                    if (serviceController1 != null)
                    {
                        serviceController1.Refresh();

                        if (serviceController1.Status == ServiceControllerStatus.Stopped)
                        {
                            if (!showstopmsg)
                            {
                                OnMSMQEvent(new MSMQEventArgs(new MSMQEntity(Entity.ConstValue.MSMQTYPE.Message, "服务已停止!")));
                            }
                            showstopmsg = true;
                        }
                        else
                        {
                            showstopmsg = false;
                        }

                        MessageQueue MQueue;

                        if (MessageQueue.Exists(ConstValue.MSMQPathToUI))
                        {
                            MQueue = new MessageQueue(ConstValue.MSMQPathToUI);
                        }
                        else
                        {
                            MQueue = MessageQueue.Create(ConstValue.MSMQPathToUI);
                            MQueue.SetPermissions("Administrators", MessageQueueAccessRights.FullControl);
                            MQueue.Label = "GCGprsMSMQ";
                        }

                        //一次读取全部消息,但是不去除读过的消息
                        System.Messaging.Message[] Msg = MQueue.GetAllMessages();
                        //删除所有消息
                        MQueue.Purge();
                        try
                        {
                            foreach (System.Messaging.Message m in Msg)
                            {
                                m.Formatter = new BinaryMessageFormatter();
                                //string msg = m.Body.ToString();
                                MSMQEntity msmqEntity = (MSMQEntity)m.Body; // (MSMQEntity)Newtonsoft.Json.JsonConvert.DeserializeObject(msg, typeof(MSMQEntity));
                                OnMSMQEvent(new MSMQEventArgs(msmqEntity));
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.ErrorException("JSON解析错误,Location:MSMQManager.MSMQReceiveThread", ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("GetServiceStatus", ex);
                OnMSMQEvent(new MSMQEventArgs(new MSMQEntity(Entity.ConstValue.MSMQTYPE.Message, ex.Message)));
            }
        }