Search This Blog

Sunday, April 3, 2011

InterProcess Communication Part2 - Using MSMQ

Here I am going to cover the topic MSMQ and how we can use MSMQ for interprocess communicatoins.
MSMQ( Microsoft Message Queuing) is one of the easiest and reliable way of sending and receiving messages between two process in the same/remote machine.
Queues can be public/private as per the requirement.
Here I will show you an example with two forms and passing messages between the forms.


Step1: Create  a named queue :
Here create a new private queue, or if the queue exists  create an instance which points to the exisitng queue . 




   1:              MessageQueue mq ;
   2:              if (MessageQueue.Exists(@".\Private$\MyQueue"))
   3:                  //creates an instance MessageQueue, which points 
   4:   
   5:                  //to the already existing MyQueue
   6:   
   7:                  mq = new System.Messaging.MessageQueue(@".\Private$\FORM1Queue");
   8:              else
   9:                  //creates a new private queue called MyQueue 
  10:   
  11:                  mq = MessageQueue.Create(@".\Private$\FORM1Queue");
  12:   
  13:   
  14:              System.Messaging.Message mm = new System.Messaging.Message();
  15:              mm.Body = "MESSAGE1";
  16:              mm.Label = "Msg" ;            
  17:              mq.Send(mm);



You can verify whether the queue is created or not with Computer Management Console. Expand, Services and Applications in Computer Management Console. Expand, Message Queuing and click Private Queue. You will find the new queue here. 






Now, let us see how to send the messages. 


Step2: Start sending and receiving messages from the above queue



   1:              System.Messaging.Message mm = new System.Messaging.Message();
   2:              mm.Body = "MESSAGE1";
   3:              mm.Label = "Msg" ;            
   4:              mq.Send(mm);
   5:              string m=null;
   6:              try
   7:              {
   8:                  System.Messaging.Message mes = mq.Receive();
   9:                  mes.Formatter = new XmlMessageFormatter(
  10:                    new String[] { "System.String,mscorlib" });
  11:                  m = mes.Body.ToString();
  12:              }
  13:              catch
  14:              {
  15:                  //m = "No Message";
  16:              }
  17:              MessageBox.Show(m);

             


No comments:

Post a Comment