C#消息队列-初见

 

C#消息队列-初见_第1张图片

1.MQ安装-https://jingyan.baidu.com/article/a17d5285df9d3e8099c8f247.html

2.using System.Messaging;

3.实际操作

  初始化

     private MessageQueue messageQueue = null;
        //消息的地址 本地和网络不一样
        private string path = @".\Private$\MyQueues";

        private void Form1_Load(object sender, EventArgs e)
        {
            //存在就实例化不存在就新建
            if (MessageQueue.Exists(path))
                messageQueue = new MessageQueue(path);
            else
                messageQueue = MessageQueue.Create(path);
            messageQueue.Label = "test messagequeue";
            messageQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
        }

  写入

            //发送消息 内容和名称
            messageQueue.Send(this.txt_text.Text, this.txt_title.Text);
            btn_read_Click(sender, e);    

  读取

            //读取所有名称
            this.listBox1.Items.Clear();


            //GetMessageEnumerator2
            var item = messageQueue.GetMessageEnumerator2();
            while (item.MoveNext())
            {
                this.listBox1.Items.Add(item.Current.LookupId + "," + item.Current.Label + "," + item.Current.Body.ToString());

                //一般情况下,处理完消息就删除掉避免再次处理
                //item.RemoveCurrent();
            }    

  删除单条

             if (this.listBox1.SelectedIndex > 0)
            {
                long msgid = Convert.ToInt64(this.listBox1.Items[this.listBox1.SelectedIndex].ToString().Split(',')[0]);
                var item = messageQueue.GetMessageEnumerator2();
                item.MoveNext();
                for (long i = item.Current.LookupId; i < msgid; i++)
                {
                    item.MoveNext();
                }
                item.RemoveCurrent();
                btn_read_Click(sender, e);
            }         

  清空

            //清除所有消息
            messageQueue.Purge();
            this.listBox1.Items.Clear();     

  

转载于:https://www.cnblogs.com/jy8888/p/11045039.html

你可能感兴趣的:(C#消息队列-初见)