c# 訊息佇列 的簡單例子

來源:互聯網
上載者:User

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

    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.