C# – The bare minimum needed to write a MSMQ sample application

cmsmq

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:

"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.

That's it… All I need for a simple demo.

Could anyone please help me with a code sample for this? Much appreciated.

Best Answer

//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

Related Topic