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;
            }

        }
    }

  • 相关阅读:
    LeetCode "Median of Two Sorted Arrays"
    LeetCode "Distinct Subsequences"
    LeetCode "Permutation Sequence"

    LeetCode "Linked List Cycle II"
    LeetCode "Best Time to Buy and Sell Stock III"
    LeetCode "4Sum"
    LeetCode "3Sum closest"
    LeetCode "3Sum"
    LeetCode "Container With Most Water"
  • 原文地址:https://www.cnblogs.com/jasonjiang/p/1763825.html
Copyright © 2011-2022 走看看