C# 编写MSMQ示例应用程序所需的最低限度

C# 编写MSMQ示例应用程序所需的最低限度,c#,msmq,C#,Msmq,我已经研究了一个多小时,找到了如何在C#中使用MSMQ的好例子,甚至是一本关于消息队列的书中的一整章……但是为了快速测试,我需要涵盖的只是这个场景,甚至不是完美的方式,只是为了快速演示: “应用程序A”:将消息写入消息队列。(应用程序A是一个C#windows服务) 现在我打开“应用程序B”(这是一个C#winForms应用程序),检查MSMQ,我看到哦,我有一条新消息 就这样。。。我只需要一个简单的演示 有人能帮我提供一个代码示例吗?非常感谢 //From Windows Service, u

我已经研究了一个多小时,找到了如何在C#中使用MSMQ的好例子,甚至是一本关于消息队列的书中的一整章……但是为了快速测试,我需要涵盖的只是这个场景,甚至不是完美的方式,只是为了快速演示:

“应用程序A”:将消息写入消息队列。(应用程序A是一个C#windows服务) 现在我打开“应用程序B”(这是一个C#winForms应用程序),检查MSMQ,我看到哦,我有一条新消息

就这样。。。我只需要一个简单的演示

有人能帮我提供一个代码示例吗?非常感谢

//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");


对于更复杂的场景,可以使用消息对象发送消息,将自己的类对象包装在其中,并将类标记为可序列化。另外,请确保您的系统上安装了MSMQ

也许下面的代码对于快速了解MSMQ很有用

因此,首先,我建议您在一个解决方案中创建3个应用程序:

  • MessageTo(Windows窗体)添加1按钮
  • MessageFrom(Windows窗体)添加1 richtextbox
  • MyMessage(类库)添加1个类
  • 只需复制过去的代码并尝试一下。确保在您的MS Windows上安装了MSMQ,并且项目1和项目2引用了
    系统。消息传递

    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);
            }
        }
    }
    
    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;
            }
        }
    }
    
    using System;
    
    namespace MyMessage
    {
        [Serializable]
        public sealed class MyMessage
        {
            public TimeSpan LifeInterval { get; set; }
    
            public DateTime BornPoint { get; set; }
    
            public string Text { get; set; }
        }
    }
    
    2。MessageFrom(Windows窗体)添加一个richtextbox。

    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);
            }
        }
    }
    
    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;
            }
        }
    }
    
    using System;
    
    namespace MyMessage
    {
        [Serializable]
        public sealed class MyMessage
        {
            public TimeSpan LifeInterval { get; set; }
    
            public DateTime BornPoint { get; set; }
    
            public string Text { get; set; }
        }
    }
    
    3。MyMessage(类库)添加一个类。

    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);
            }
        }
    }
    
    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;
            }
        }
    }
    
    using System;
    
    namespace MyMessage
    {
        [Serializable]
        public sealed class MyMessage
        {
            public TimeSpan LifeInterval { get; set; }
    
            public DateTime BornPoint { get; set; }
    
            public string Text { get; set; }
        }
    }
    

    享受:)

    什么是反对票?如果你对这个话题有所了解,那就教我们其他人。@Sascha:读我文章的开头:“我已经研究了一个多小时,找到了如何在C#中使用MSMQ的好例子,甚至是一本关于消息队列的书中的一整章……但是对于一个快速测试,我需要涵盖的只是这个场景,甚至不是一个完美的方式,只是为了一个快速演示“MSMQ中的问题也请查看这篇MSDN文章问题:在顶部,您正在创建MessageQueue,我们需要这两个吗?”?MessageQueue.Create(@“\Private$\SomeTestName”);messageQueue=newmessagequeue(@“.\Private$\SomeTestName”);是的,你需要这两个语句,一个实际上创建了一个MSMQ,另一个只是初始化了MSMQ,路径像一个符咒一样工作…希望你的愿望今天实现…你今天为我解决了一件大事。小错误:messageQueue=newmessagequeue(@“\Private$\SomeTestName”);System.Messaging.Message[]messages=queue.GetAllMessages();应该是messageQueue=newmessagequeue(@.\Private$\SomeTestName”);System.Messaging.Message[]messages=messageQueue.GetAllMessages();要将队列的输出打印到控制台,请在输出循环的主体中添加“message.Formatter=new XmlMessageFormatter(新字符串[]{”System.String,mscorlib“});console.Write(message.body.ToString());”。当MSMQ将事物作为序列化对象传递时,您必须告诉它如何将接收到的对象反序列化为其原始形式。MSQueue线程安全?使用同一MSQueue的多个EXE应用程序?GetAllMessages和Purgue有什么用?@Kiquenet我希望它能帮助你