zoukankan      html  css  js  c++  java
  • .net中使用消息传递数据

    使用消息传递数据时,一般情况下数据量较少。在我所使用的项目中,使用它最大的好处就是不用考虑对方是否是运行状态,只要对方上线,它就可能收到。在项目中,它的作用是在产生较大的数据时,先用消息进行通知,在对方收到消息后,再从Web服务来收取,代码如下,有改动:

    发送端:

     1            messageModel.transfersModel tmodel = new messageModel.transfersModel(sourcetext.Trim(), itype, content.Trim());
     2            using (MessageQueue queue = new MessageQueue("FormatName:DIRECT=tcp:" + address.Trim() + @"\Private$\message"))
     3            {
     4                MessageQueueTransaction transMes = new MessageQueueTransaction();
     5                try
     6                {
     7                    transMes.Begin();
     8                    queue.Send(tmodel, "transferMessage : { " + sourceip.Trim() + " }");
     9                    transMes.Commit();
    10                }

    11                catch
    12                {
    13                    transMes.Abort();
    14                }

    15            }

    16

    接收端:
     1        private Thread receiveMessageThread;
     2
     3        private void Form_Load(object sender, EventArgs e)
     4        {
     5            ///接收消息
     6            this.queue = new MessageQueue(@".\Private$\tgatemessage");
     7            System.Type[] types = new Type[] typeof(messageModel.transfersModel) };
     8            queue.Formatter = new XmlMessageFormatter(types);
     9
    10            this.receiveMessageThread = new Thread(new ThreadStart(this.getMessage));
    11            this.receiveMessageThread.IsBackground = true;
    12            this.receiveMessageThread.Start();
    13        }

    14
    15
    16
    17        接收消息
    45
    46

    接收端使用一个单独的线程来监测消息,而消息的读取本身具有阻塞,所以在没有新消息时此线程处于停止状态,在有新的消息时才运行,运行完成后再次阻塞。发送端与接收端共用了一个数据类,内容可根据自己的需要进行定义。
  • 相关阅读:
    假如我国国民生产总值的年增长率为7%, 计算10年后我国国民生产总值与现在相比增长多少百分比。计算公式为$p = (1+r)^n$ ,其中r为年增长率,n为年数,p为与现在相比的倍数
    不定积分40例
    docker容器
    Kubernetes搭建
    windows提权之mimikatz
    NodeJS沙箱逃逸&&vm
    jwt攻击手段
    yii2邮件配置教程,报Expected response code 250 but got code "553"原因
    git 撤销,放弃本地修改
    动态规划(含最短路径和正则匹配例子)
  • 原文地址:https://www.cnblogs.com/wjhx/p/908490.html
Copyright © 2011-2022 走看看