写一个MSMQ示例应用程序所需要的最低限度

问题描述 投票:108回答:2

我一直在研究了一个多小时,并找到了如何在C#中使用MSMQ大样本,甚至有一本关于消息队列的整整一章......但对于一个快速测试所有我需要的是盖这种情况下,即使不在一个完美的方式,只是一个快速演示:

“应用程序A”:将消息写入消息队列。 (应用程序A是C#窗口服务)现在,我打开“应用程序B”(这是一个C#WinForms应用程序),我检查MSMQ,我看啊,我有一个新的消息。

就是这样...所有我需要一个简单的演示。

任何人都可以请帮我这一个代码示例?非常感激。

c# msmq
2个回答
131
投票
//From Windows Service, use this code
MessageQueue messageQueue = null;
if (MessageQueue.Exists(@".\Private$\SomeTestName"))
{
    messageQueue = new MessageQueue(@".\Private$\SomeTestName");
    messageQueue.Label = "Testing Queue";
}
else
{
    // Create the Queue
    MessageQueue.Create(@".\Private$\SomeTestName");
    messageQueue = new MessageQueue(@".\Private$\SomeTestName");
    messageQueue.Label = "Newly Created Queue";
}
messageQueue.Send("First ever Message is sent to MSMQ", "Title");

//From Windows application
MessageQueue messageQueue = new MessageQueue(@".\Private$\SomeTestName");
System.Messaging.Message[] messages = messageQueue.GetAllMessages();

foreach (System.Messaging.Message message in messages)
{
    //Do something with the message.
}
// after all processing, delete all the messages
messageQueue.Purge();

对于更复杂的情况下,您可以使用的消息对象发送消息,包裹里面你自己的类的对象,并且你的类为可序列化。另外要确保MSMQ被安装在系统上


13
投票

也许有人只得到迅速介绍到MSMQ下面的代码将是有益的。

所以开始我建议你创建一个解决方案3个应用程序:

  1. 邮件要(Windows窗体)添加1个按钮。
  2. 消息从(Windows窗体)加1周的RichTextBox。
  3. MyMessage(类库)加1级。

只需复制过去的代码和尝试。确保MSMQ上安装了MS Windows和项目1和2有参考System.Messaging

1. MessageTo(Windows窗体)添加1个按钮。

using System;
using System.Messaging;
using System.Windows.Forms;

namespace MessageTo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            #region Create My Own Queue 

            MessageQueue messageQueue = null;
            if (MessageQueue.Exists(@".\Private$\TestApp1"))
            {
                messageQueue = new MessageQueue(@".\Private$\TestApp1");
                messageQueue.Label = "MyQueueLabel";
            }
            else
            {
                // Create the Queue
                MessageQueue.Create(@".\Private$\TestApp1");
                messageQueue = new MessageQueue(@".\Private$\TestApp1");
                messageQueue.Label = "MyQueueLabel";
            }

            #endregion

            MyMessage.MyMessage m1 = new MyMessage.MyMessage();
            m1.BornPoint = DateTime.Now;
            m1.LifeInterval = TimeSpan.FromSeconds(5);
            m1.Text = "Command Start: " + DateTime.Now.ToString();

            messageQueue.Send(m1);
        }
    }
}

2. MessageFrom(Windows窗体)加1周的RichTextBox。

using System;
using System.ComponentModel;
using System.Linq;
using System.Messaging;
using System.Windows.Forms;

namespace MessageFrom
{
    public partial class Form1 : Form
    {
        Timer t = new Timer();
        BackgroundWorker bw1 = new BackgroundWorker();
        string text = string.Empty;

        public Form1()
        {
            InitializeComponent();

            t.Interval = 1000;
            t.Tick += T_Tick;
            t.Start();

            bw1.DoWork += (sender, args) => args.Result = Operation1();
            bw1.RunWorkerCompleted += (sender, args) =>
            {
                if ((bool)args.Result)
                {
                    richTextBox1.Text += text;
                }
            };
        }

        private object Operation1()
        {
            try
            {
                if (MessageQueue.Exists(@".\Private$\TestApp1"))
                {
                    MessageQueue messageQueue = new MessageQueue(@".\Private$\TestApp1");
                    messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MyMessage.MyMessage) });


                    System.Messaging.Message[] messages = messageQueue.GetAllMessages();

                    var isOK = messages.Count() > 0 ? true : false;
                    foreach (System.Messaging.Message m in messages)
                    {
                        try
                        {
                            var command = (MyMessage.MyMessage)m.Body;
                            text = command.Text + Environment.NewLine;
                        }
                        catch (MessageQueueException ex)
                        {
                        }
                        catch (Exception ex)
                        {
                        }
                    }                   
                    messageQueue.Purge(); // after all processing, delete all the messages
                    return isOK;
                }
            }
            catch (MessageQueueException ex)
            {
            }
            catch (Exception ex)
            {
            }

            return false;
        }

        private void T_Tick(object sender, EventArgs e)
        {
            t.Enabled = false;

            if (!bw1.IsBusy)
                bw1.RunWorkerAsync();

            t.Enabled = true;
        }
    }
}

3. MyMessage(类库)加1级。

using System;

namespace MyMessage
{
    [Serializable]
    public sealed class MyMessage
    {
        public TimeSpan LifeInterval { get; set; }

        public DateTime BornPoint { get; set; }

        public string Text { get; set; }
    }
}

请享用 :)

© www.soinside.com 2019 - 2024. All rights reserved.