当前位置:   article > 正文

微软 消息队列 MessageQueue 简单使用_queue message journal message

queue message journal message

转自http://www.cnblogs.com/lixipeng/p/5886150.html

微软 消息队列 MessageQueue 简单使用

1.在服务电脑上打开 消息队列

①进入控制面板》程序》启用或关闭windows功能

 

②将需要的勾选(我自己全选了哈哈哈)

③我的电脑 右键 打开管理 见到消息队列 在专用队列上新建专用队列

 

 ⑤填写名称还有选择是否是事务性

 

好到这里就基本准备完成

 

下面就要使用队列 来发送消息

复制代码

           //创建消息队列 并发送消息到队列
            try
            {
                //连接到本地新创建的队列 
                MessageQueue myQueue = new MessageQueue(".\\private$\\test2");
                //创建一个消息
                System.Messaging.Message myMessage = new System.Messaging.Message();
                //给消息体赋值
                myMessage.Body = "你好我是消息体";
                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                //发送消息到队列中(创建队列时勾选了事务性之后 不能直接使用 public void Send(object obj) 这个方法 因为其不支持事务)
             
                // 我要使用下面这个支持事务的发送方法
                myQueue.Send(myMessage,System.Messaging.MessageQueueTransactionType.Single);

            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }

复制代码


发完消息之后就要接收消息

消息的接受使用Receive()方法

但是该方法会阻塞线程

所以建议将其放到一个独立的线程中,不让其影响其他线程的运行

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

//创建一个任务 让其不断的在接收消息队列发出的消息

Task t = Task.Factory.StartNew(() => {

    while (true)

    {

        //创建队列 要跟发消息的队列同一个名称

        MessageQueue mq = new MessageQueue(@".\private$\test2");

 

        // 如果不用多线程就会阻塞在Receive

        System.Messaging.Message m = mq.Receive();

 

        //定义内容格式

        m.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });

 

        //接收到消息后 回去更新主线程的UI界面

        Action<String> AsyncUIDelegate = delegate (string n)

        {

            this.ReceiveText2.Text = n; //对ui的操作

        };//定义一个委托

        this.ReceiveText2.Invoke(AsyncUIDelegate, new object[] { m.Body.ToString() });

    }

});

测试效果:


啊啊啊啊 要记住勾选了事务性 不要用send(object ) 这个方法呀

1

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/956939
推荐阅读
相关标签
  

闽ICP备14008679号