⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 msgqueue.cs

📁 MSMQ之使用範例程式
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Messaging;

namespace MSMQ.App
{
    public class MsgQueue
    {
        /// <summary>
        /// 通过Create方法创建使用指定路径的新消息队列
        /// </summary>
        /// <param name="queuePath"></param>
        public static void Createqueue(string queuePath)
        {
            try
            {
                if (!MessageQueue.Exists(queuePath))
                {
                    MessageQueue.Create(@".\private$\myQueue");
                    MessageBox.Show("创建队列成功!");
                }
                else
                {
                    MessageBox.Show(queuePath + "已经存在!");
                }
            }
            catch (MessageQueueException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        /// <summary>
        /// 连接消息队列并发送消息到队列
        /// </summary>
        public static bool SendMessage(Book book)
        {
            bool flag = false;
            try
            {
                //连接到本地的队列
                MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");

                System.Messaging.Message myMessage = new System.Messaging.Message();
                myMessage.Body = book;
                myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) });
                //发送消息到队列中
                myQueue.Send(myMessage);
                flag = true;
            }
            catch (ArgumentException e)
            {
                MessageBox.Show(e.Message);
            }
            return flag;
        }

        /// <summary>
        /// 连接消息队列并从队列中接收消息
        /// </summary>
        public static string ReceiveMessage()
        {
            //连接到本地队列
            MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQ.App.Book) });
            try
            {
                //从队列中接收消息
                System.Messaging.Message myMessage = myQueue.Receive();
                Book book = (Book)myMessage.Body; //获取消息的内容
                return string.Format("编号:{0},书名:{1},作者:{2},定价:{3}",
                    book.BookId,
                    book.BookName,
                    book.BookAuthor,
                    book.BookPrice);
            }
            catch (MessageQueueException e)
            {
                MessageBox.Show(e.Message);
            }
            catch (InvalidCastException e)
            {
                MessageBox.Show(e.Message);
            }
            return null;
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -