c# msmq的简单操作

来源:互联网 发布:android ndk mac 下载 编辑:程序博客网 时间:2024/06/08 09:07
     
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Messaging;//测试msmq的功能namespace TestMQ{    class Program    {        /**/        /// <summary>         /// 通过Create方法创建使用指定路径的新消息队列         /// </summary>         /// <param name="queuePath"></param>         public static void Createqueue(string queuePath)        {            try            {                if (!MessageQueue.Exists(queuePath))                {                    MessageQueue.Create(@".\private$\emporer");                }                else                {                    Console.WriteLine(queuePath + "已经存在!");                }            }            catch (MessageQueueException e)            {                Console.WriteLine(e.Message);            }        }        /**/        /// <summary>         /// 连接消息队列并发送消息到队列         /// </summary>         public static void SendMessage()        {            try            {                //连接到本地的队列                 MessageQueue myQueue = new MessageQueue(@".\private$\emporer");                Message myMessage = new Message();                myMessage.Body = "22222222222222222";                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });                //发送消息到队列中                 myQueue.Send(myMessage);            }            catch (ArgumentException e)            {                Console.WriteLine(e.Message);            }        }        /**/        /// <summary>         /// 连接消息队列并从队列中接收消息         /// </summary>         public static void ReceiveMessage()        {            //连接到本地队列             MessageQueue myQueue = new MessageQueue(".\\private$\\emporer");            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });            try            {                //从队列中接收消息                 Message myMessage = myQueue.Receive();                string context = (string)myMessage.Body; //获取消息的内容                 Console.WriteLine("消息内容为:" + context);            }            catch (MessageQueueException e)            {                Console.WriteLine(e.Message);            }            catch (InvalidCastException e)            {                Console.WriteLine(e.Message);            }        }        /**/        /// <summary>         /// 清空指定队列的消息         /// </summary>         public static void ClearMessage()        {            MessageQueue myQueue = new MessageQueue(".\\private$\\emporer");            myQueue.Purge();        }        static void Main(string[] args)        {            Program.SendMessage();            Program.ReceiveMessage();            Console.ReadLine();        }    }}

0 0
原创粉丝点击