Thursday, November 8, 2012

Windows Message Queue (MSMQ) Using C#.Net

This article is about creating windows message queue using C#.NET.


In this article we will create a private queue example. Lets develop an app and understand how the private queue works


 1) Create a console application using Visual Studio

 2) In Program.cs create a static method to create/get a private queue. Don't forget to include the "System.Messaging" namespace

private static MessageQueue GetStringMessageQueue()
 {
 MessageQueue msgQueue = null;
 string queueName = @".\private$\MyStringQueue";
 if (!MessageQueue.Exists(queueName))
 {
 msgQueue = MessageQueue.Create(queueName );
 }
 else
 {
 msgQueue = new MessageQueue(queueName );
 }
 return msgQueue;
 }

3) So now we have the queue, lets send a message as given below

private static void SendStringMessageToQueue()
 {
 MessageQueue msgQueue = GetStringMessageQueue();
 msgQueue.Send("New Message send to message queue at "+ DateTime.Now.ToString());
 }

4) Given below is the function to read the message from queue

private static void ReadStringMessageFromQueue()
 {
 MessageQueue msgQueue = GetStringMessageQueue();
 msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
 Message msg = msgQueue.Receive(); Console.WriteLine(msg.Body.ToString());
 }

5) That's it! Now lets call the functions from 'static main'

static void Main(string[] args)
 {
 SendStringMessageToQueue();
 ReadStringMessageFromQueue();
 Console.ReadLine();
 }


Wasn't that easy! Well this is the basic queue...to make it more useful you have to send the message from one thread and read from another thread or application.

 Happy coding guys!

No comments: