1.启用MSMQ

 

 

MSMQ简单实例

2.首先添加引用

using System.Messaging;
3.发送消息到消息队列

public partial class Form1 : Form
    {
        private MessageQueue mq;
        public Form1()
        {
            InitializeComponent();
            //新建消息循环队列或连接到已有的消息队列
            string path = ".\\private$\\killf";
            mq = MessageQueue.Exists(path) ? new MessageQueue(path) : MessageQueue.Create(path);
            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            mq.Send(this.textBox1.Text);
        }
    }

4.从消息队列取数据处理

    public partial class Form1 : Form
    {
        MessageQueue mq;
        public Form1()
        {
            InitializeComponent();
            //新建消息循环队列或连接到已有的消息队列
            string path = ".\\private$\\killf";
            mq = MessageQueue.Exists(path) ? new MessageQueue(path) : MessageQueue.Create(path);
            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            mq.ReceiveCompleted += mq_ReceiveCompleted;
            mq.BeginReceive();
    }

    private void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
    {
        //throw new NotImplementedException();
        MessageQueue mq = (MessageQueue)sender;
        System.Messaging.Message m = mq.EndReceive(e.AsyncResult);
        //处理消息
        string str = m.Body.ToString();
            ShowMsg(str);
            //继续下一条消息
            mq.BeginReceive();
    }

        private void ShowMsg(string msg)
        {
            this.textBox1.Text += msg + Environment.NewLine;

            return;
        }
    
 

相关文章:

  • 2021-11-30
  • 2021-11-19
  • 2021-05-30
  • 2022-01-08
  • 2021-07-24
  • 2021-09-13
  • 2021-11-30
猜你喜欢
  • 2021-10-04
  • 2022-03-10
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2021-12-14
  • 2021-05-01
相关资源
相似解决方案