zoukankan      html  css  js  c++  java
  • c# 消息队列 的简单例子

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Messaging;


    namespace QueueTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                string path = @".\private$\test";

                if (MessageQueue.Exists(path))
                {
                    MessageQueue.Delete(path);
                }
                //创建一个消息队列 并发送
                MessageQueue msq = MessageQueue.Create(path);
                msq.Send(8);
                msq.Send("Jason");

                Mathes mm = new Mathes();
                msq.Send(mm);
                msq.Send(mm);

                //出队
                ((XmlMessageFormatter)msq.Formatter).TargetTypes = new Type[] { typeof(System.Int32) };
                Message m1 = msq.Receive();

                Console.WriteLine(m1.Body.ToString());

                ((XmlMessageFormatter)msq.Formatter).TargetTypes = new Type[] { typeof(System.String) };
                Message m2 = msq.Receive();
           
                Console.WriteLine(m2.Body.ToString());

                ((XmlMessageFormatter)msq.Formatter).TargetTypes = new Type[] { typeof(Mathes) };
                Message m3 = msq.Receive();
                Console.WriteLine(mm.SumAB(10,20));

                #region 异步

                ((XmlMessageFormatter)msq.Formatter).TargetTypes = new Type[] { typeof(Mathes) };
                msq.BeginReceive(new TimeSpan(10000), msq, new AsyncCallback(MySum));

                #endregion

                Console.Read();
            }

            static void MySum(IAsyncResult ia)
            {
                MessageQueue msq = ia.AsyncState as MessageQueue;

                Message m4 = msq.EndReceive(ia);

                Mathes mm = m4.Body as Mathes;

                Console.WriteLine(mm.SumAB(25, 35));
            }
        }
        public class Mathes
        {
            private int a = 25;

            private string b = "35";

            public string B
            {
                get { return b; }
                set { b = value; }
            }

            public int A
            {
                get { return a; }
                set { a = value; }
            }

            public int SumAB(int a, int b)
            {
                return a + b;
            }

        }
    }

  • 相关阅读:
    理论+实践解析“IT治理”之模式与原则
    iOS开发如何避免安全隐患
    DBA职业发展之路:去“IOE”等挑战之下,DBA将何去何从?
    自动化测试最佳实践(一):从纺锤模型到金字塔模型
    宜信开源|手把手教你安装第一个LAIN应用
    宜信开源|数据库审核软件Themis的规则解析与部署攻略
    开源|性能优化利器:数据库审核平台Themis的选型与实践
    小老板,我300M的网,网速很慢怎么办?
    JSP、ASP、PHP Web应用程序怎么这么多P!
    难道你现在还不知道:C/S和B/S
  • 原文地址:https://www.cnblogs.com/jasonjiang/p/1763825.html
Copyright © 2011-2022 走看看