Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C#
Article

Using MSMQ from C#

Rate me:
Please Sign up or sign in to vote.
4.48/5 (43 votes)
11 Jan 20043 min read 370.2K   12.8K   97   13
Using MSMQ from C#

Introduction

Microsoft Windows Message Queuing is the easy way to communicate with application programs quickly and reliably by sending and receiving messages. Messaging provides a flexible and powerful mechanism for inter-process communication between the components of server-based applications.

It provides you with guaranteed message delivery. You can prioritize your messages according to your needs. Messages can be sent and remain in the queue the same way as it sent till the message is delivered. In other words, you can implement offline capabilities. Several related messages can be coupled into a single transaction to ensure that they are sent in order, delivered only once and successfully retrieved in the destination queue. If any error occurs in this transaction, the transaction is cancelled. You can use Windows security to secure access control, authenticate and encrypt the messages you send and receive.

This article attempts to explain the how MSMQ can be implemented between two forms and the very basics of message queuing. Here are the two forms.

Image 1

Image 2

Details

When you enter a message in the textbox and click send, it sends the message to the other form. When you click Receive, you get the message what the other form has sent. When there is no message in the queue, it says ‘No Message’.

Let me start with the queue creation. Here, I create a private queue called ‘MyQueue’. You can create public queues on your machine or any machine with Message Queuing. For that, you need to have domain or enterprise administrative access rights. There is a difference in creating a queue and creating an instance of Message Queuing component, which refers to an already existing queue in the operating system. This code snippet says, if the private queue called MyQueue exist, create an instance of MessageQueue to point to that queue. Else, create a private queue called MyQueue

C#
if(MessageQueue.Exists(@".\Private$\MyQueue"))
      //creates an instance MessageQueue, which points 
      //to the already existing MyQueue
      mq = new System.Messaging.MessageQueue(@".\Private$\MyQueue");
else
      //creates a new private queue called MyQueue 
      mq = MessageQueue.Create(@".\Private$\MyQueue");

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’ll find MyQueue here. Now, let us see how to send the messages.

C#
System.Messaging.Message mm = new System.Messaging.Message();
mm.Body = txtMsg.Text;
mm.Label = "Msg" + j.ToString();
j++;
mq.Send(mm);

Use Message object to send messages. This will give you more control over your messages. To receive,

C#
try
{
      mes = mq.Receive(new TimeSpan(0, 0, 3));
      mes.Formatter = new XmlMessageFormatter(
        new String[] {"System.String,mscorlib"});
      m = mes.Body.ToString();
}
catch
{
      m = "No Message";
}
MsgBox.Items.Add(m.ToString());

There are several considerations in retrieving and reading messages from the queue. They are locking access, properties and format for reading messages. Here, I’ve dealt with format only. To read messages from a queue, a formatter is necessary to serialize and deserialize the message before manipulating it. I’ve used XmlMessageFormatter here.

You can set a series of properties to indicate what properties you want to retrieve when the component gets a message from a queue. You can find these properties in a class called MessagePropertyFilter Class and it corresponds to actual properties on the Message class. When you set the value for one of these properties to true, the component will retrieve the corresponding property each time a message is removed from the queue. If you don’t want to retrieve any property, you can set the MessagePropertyFilter to false.

You can lock access to the queue by setting the DenySharedReceive property to false. This will help temporarily prevents other users to read message from the queue you are working and also prevents from removing messages.

Put the creation logic in the constructor of the form and the send and receive in appropriate button clicks, you’ll get the simple inter-process communication between the two forms.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
United States United States
Architect / Consultant on Content Management and Cloud Computing... Artist and Author by the weekends...

Comments and Discussions

 
GeneralMy vote of 1 Pin
dallas1234522-Aug-09 14:18
dallas1234522-Aug-09 14:18 
Questioncan't install MSMQ Pin
prolingua.geo28-May-09 23:04
prolingua.geo28-May-09 23:04 
AnswerRe: can't install MSMQ Pin
LesF3-Dec-09 10:38
LesF3-Dec-09 10:38 
GeneralGreat introduction Pin
DUMITRU Guraliuc8-Apr-09 20:31
DUMITRU Guraliuc8-Apr-09 20:31 
GeneralTerrible example Pin
AlanSimes20-Nov-06 21:24
AlanSimes20-Nov-06 21:24 
GeneralRe: Terrible example Pin
LesF3-Dec-09 10:33
LesF3-Dec-09 10:33 
There is so much wrong with that comment (ok, it was posted several years ago, but it serves little purpose in still existing here).

"Exists" appears to work just fine, in the context of this example application. If somebody knows a good reason to not use "Exists", please post some helpful explanation here.
GeneralVery Urgent Pin
Shiv55-Jun-06 19:54
Shiv55-Jun-06 19:54 
GeneralMultiple Clients over the internet Pin
gianmaria24-Feb-06 2:33
gianmaria24-Feb-06 2:33 
GeneralObjects Pin
gianmaria24-Feb-06 2:12
gianmaria24-Feb-06 2:12 
GeneralRe: Objects Pin
Bested7-May-06 23:10
Bested7-May-06 23:10 
GeneralRe: Objects Pin
SupermanDT2-Jun-06 11:44
SupermanDT2-Jun-06 11:44 
GeneralMessaging not installed Pin
Oldnavigator19-Jan-06 22:16
Oldnavigator19-Jan-06 22:16 
GeneralRe: Messaging not installed Pin
awj10023-Feb-06 8:32
awj10023-Feb-06 8:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.