C# 编写 MSMQ 示例应用程序所需的最低限度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11076790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The bare minimum needed to write a MSMQ sample application
提问by Bohn
I have been researching for over an hour and finding great samples of how to use MSMQ in C# and even one full chapter of a book about Message Queue...But for a quick test all I need is to cover is this scenario, not even in a perfect way, just for a quick demo:
我已经研究了一个多小时,并找到了如何在 C# 中使用 MSMQ 的很好的示例,甚至是一本关于 Message Queue 的书的一整章……但是为了快速测试,我只需要涵盖这个场景,甚至没有以完美的方式,仅用于快速演示:
"Application A": Writes a Message to Message Queue. ( Application A is a C# windows service) Now I open "Application B" ( it is a C# winForms app ) and I check MSMQ and I see oh I have a new Message.
“应用程序 A”:将消息写入消息队列。(应用程序 A 是一个 C# windows 服务)现在我打开“应用程序 B”(它是一个 C# winForms 应用程序)并检查 MSMQ,我看到哦,我有一个新消息。
That's it... All I need for a simple demo.
就是这样......我需要一个简单的演示。
Could anyone please help me with a code sample for this? Much appreciated.
任何人都可以帮我提供一个代码示例吗?非常感激。
采纳答案by Anand
//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();
For more complex scenario, you could use Message objects to send the message, wrap your own class object inside it, and mark your class as serializable. Also be sure that MSMQ is installed on your system
对于更复杂的场景,您可以使用 Message 对象发送消息,将您自己的类对象包装在其中,并将您的类标记为可序列化。还要确保您的系统上安装了 MSMQ
回答by Developer
Perhaps code below will be useful for someone to just get quick intro to MSMQ.
也许下面的代码对于快速介绍MSMQ 的人会很有用。
So to start I suggest that you create 3 apps in a solution:
因此,首先我建议您在解决方案中创建 3 个应用程序:
- MessageTo (Windows Form) Add 1 button.
- MessageFrom (Windows Form) Add 1 richtextbox.
- MyMessage (Class Library) Add 1 class.
- MessageTo (Windows 窗体) 添加 1 个按钮。
- MessageFrom (Windows Form) 添加 1 个富文本框。
- MyMessage(类库) 添加 1 个类。
Just copy past code and try it. Make sure that MSMQ is installedon your MS Windows and projects 1 and 2 have reference to System.Messaging.
只需复制过去的代码并尝试一下。确保MSMQ 安装在您的 MS Windows 上,并且项目 1 和 2 引用了System.Messaging.
1. MessageTo (Windows Form) Add 1 button.
1. MessageTo (Windows Form) 添加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 Form) Add 1 richtextbox.
2. MessageFrom (Windows Form) 添加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 (Class Library) Add 1 class.
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; }
}
}
Enjoy :)
享受 :)

