新建一个消息队列并监听它

private readonly string QueueKey = ConfigurationManager.AppSettings["QueueKey"].ToString().Trim();
        /// <summary>
        /// 写入消息队列
        /// </summary>
        /// <param name="str"></param>
        public void SendQueue(string str, string lable)
        {
            try
            {
                MessageQueue myQueue = new MessageQueue(QueueKey);
                System.Messaging.Message myMessage = new System.Messaging.Message();
                myMessage.Body = str;
                myMessage.Label = lable;
                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                myQueue.Send(myMessage, System.Messaging.MessageQueueTransactionType.Single);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
/// <summary>
        /// 接收queue消息
        /// </summary>
        private void StartQueueLog() {
            Task t = Task.Factory.StartNew(() => {
                while (true)
                {
                    if (!MessageQueue.Exists(QueueKey))
                        MessageQueue.Create(QueueKey);
                    MessageQueue mq = new MessageQueue(QueueKey);
                    System.Messaging.Message m = mq.Receive();
                    m.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                    Action<String, String> AsyncUIDelegate = delegate (string type, string n)
                    {
                        //提示信息
                        this.JobLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "\r\n" + n + "\r\n");
                    };
                    this.JobLog.Invoke(AsyncUIDelegate, new object[] { m.Label.ToString(), m.Body.ToString() });
                }
            });
        }

  

猜你喜欢

转载自www.cnblogs.com/yuchenghao/p/10246020.html