Friday, November 9, 2012

Windows Message Queue (MSMQ) with Threading using C#.NET

In last post we learned how to create a simple message queue. In this article we are going to write a C# app to use the message queue in thread, so that one thread can be used to send messages and other to read it.


1) Create a console application in C#

2) Declare class level variable

   static bool StopThread = false;

2) Write function to get message queue instance


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)  Create function to send message to queue


  private static void SendStringMessageToQueue()
        {
            while (StopThread == false)
            {
                string msg = Console.ReadLine();
                if (msg == "x")
                {
                    Console.WriteLine("Stopping write thread...");
                    StopThread = true;
                    break;
                }
                else
                {
                    MessageQueue msgQueue = GetStringMessageQueue();
                    msgQueue.Send("New Message send to message queue at " + DateTime.Now.ToString() + "- " + msg);
                }
            }
        }


4) Create function to read message


    private static void ReadStringMessageFromQueue()
        {
            MessageQueue msgQueue = GetStringMessageQueue();
            msgQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });

            Message msg;
            while (StopThread == false)
            {            
                if (StopThread == true)
                {
                    Console.WriteLine("Stopping read thread...");
                    break;
                }
                try
                {
                    msg = msgQueue.Receive(new TimeSpan(0, 0, 2));
                    Console.WriteLine(msg.Body.ToString());
                }
                catch (Exception ex)
                {
                }
            }
        }

5) Now create threads within static main method


  static void Main(string[] args)
        {
            Console.WriteLine("Press x to stop thread");

            Thread sendMsgThread =  new Thread(new ThreadStart(SendStringMessageToQueue));
            Thread readMsgThread = new  Thread(new ThreadStart(ReadStringMessageFromQueue));

            sendMsgThread.Start();
            readMsgThread.Start();
         
        }

No comments: