Use Microsoft Message Queue for C # inter-process communication

Source: Internet
Author: User

As the name suggests, Microsoft Message Queue (MSMQ) is a method for sending messages to queues for later processing. A message is sent by a Producer application and then returned by a Consumer application.

54ne.com

These two applications can be deployed on the same machine, across the network, or even on different machines that are not always connected together. MSMQ is fault-free because it resends messages if the first transmission fails. This ensures that your application messages reach their destination.

54com.cn

I will apply a queue called "TechRepublic. When you run the sample instance in the downloaded version of this article, if the queue does not exist, it will be automatically created. 54com.cn

In the previous article, Zach Smith explains how to use the IPC channel to communicate between two processes on the same machine. This document describes how to implement inter-process communication between applications on the same machine or network. Feedom.net

Access MSMQ

Www.bitscn.com

The. NET access queue is completed by the System. Messaging. MessageQueue object. List A illustrates how to access the TechRepublic queue on A computer named SRV-MESSAGING.

54ne.com

List

China Network Management Forum bbs.bitsCN.com

MessageQueue queue = new MessageQueue ("SRV-MESSAGINGTechRepublic ");

Feedom.net

Note: To apply this object, you must add a reference in your project.

China Network Management Alliance www, bitsCN, com

Now we have a MessageQueue object, which provides all the functions required for interaction with the queue. 54ne.com

If the queue does not exist, you can call the static Create method of the MessageQueue object to program the establishment of the queue. The code in list B shows how to check whether a queue exists, create a queue, or add a reference to the queue. China Network Management Alliance www, bitsCN, com

List B Network Management Network bitsCN_com

MessageQueue queue = null;

China Network Management Alliance www, bitsCN, com

String queueName = "SRV-MESSAGINGTechRepublic ";

Network Management Network bitsCN.com

If (MessageQueue. Exists (queueName ))

China Network Management Alliance www, bitsCN, com

Queue = newMessageQueue (queueName );

Network Management Network bitsCN.com

Else

China Network Management Alliance www_bitscn_com

Queue = MessageQueue. Create (queueName, false); www.bitscn.com

54ne.com

Rewrite queue 54com.cn

The MessageQueue. Send method is used to rewrite the queue. Example C shows how to send a message to the TechRepublic queue.

China Network Management Forum bbs.bitsCN.com

List C China Network Management Alliance www.bitscn.com

Queue. Send ("My message body", "Message Label ");

Www.bitscn.com

In this example, we send a message whose body is "My Message body" to the TechRepublic queue and apply a "message Label" Label to the Message. Message tags allow you to split messages without reading the message body. If you want to view the queue from the computer management console, you can also see these labels in the "queue message" section.

54ne.com

Read queue

Www.bitscn.com

You can use several methods to read messages from a queue. The most common case is to retrieve all messages from the queue and process them at one time. Call the MessageQueue. GetAllMessages method. List D illustrates how to apply this method. Network Management Network bitsCN.com

List D

System. Messaging. Message [] messages = queue. GetAllMessages ();

Foreach (System. Messaging. Message message in messages)

China Network Management Alliance www_bitscn_com

{54com.cn

// Do something with the message. Net bitsCN_com

}

Network Management Alliance www.bitsCN.com

Feedom.net

You can also use the GetMessageEnumerator2 method to replace the MessageQueue. GetAllMessages method above. Although the usage of the two methods is similar, GetMessageEnumerator2 can only forward (forward-only ). For a very large queue, the application uses this method instead of the MessageQueue. GetAllMessages method.

Network Management Network bitsCN.com

This is because the GetAllMessages method receives all the messages and stores them in the local memory. The GetMessageEnumerator2 method only receives the current message and saves it locally. It receives the next message only when MoveNext is called. List E illustrates how to use the GetMessageEnumerator2 method. This code checks each message in the queue and then deletes it.

MessageEnumerator enumerator = queue. GetMessageEnumerator2 (); www.bitscn.com

While (enumerator. MoveNext () China Network Management Alliance www, bitsCN, com

Enumerator. RemoveCurrent (); China Network Management Forum bbs.bitsCN.com

China Network Management Alliance www_bitscn_com

When using the GetMessageEnumerator2 method, consider another problem, that is, you want to access any new messages added to the queue, even if they are added after you call GetMessageEnumerator2. This assumes that the new message is added to the end of the queue.

54com.cn

If you only want to return the first message in the queue, you should use the MessageQueue. Receive method. This method will receive the first message in the queue and delete it from the queue during this process. Because the message is deleted when it is read, you can ensure that your process is the only process that receives the message. The application of the Receive method is shown in list F.

China Network Management Forum bbs.bitsCN.com

List of F China Network Management Forum bbs.bitsCN.com

System. Messaging. Message message = queue. Receive ();
54ne.com

You can use the Peek method instead of the Receive method. The Peek method obtains the first message in the queue like the Receive method. However, it retains the message backup in the queue. This allows you to check the message content before deleting a message from the queue. The syntax of Peek is similar to that of Receive.

54ne.com

List G

China Network Management Alliance www, bitsCN, com

System. Messaging. Message message = queue. Peek ();

China Network Management Alliance www_bitscn_com

Send/receive serialized object

Network Management Network bitsCN.com

Although the function of sending text to a queue is very useful, the queue also allows you to send serializable objects. This means you can create a custom. NET class, instantiate an instance of it, and send it to the queue for other applications to use. To complete this process, you must first use XML Serializer to serialize the sent object and then put the serialized object into the message body.

54com.cn

For example, suppose we want to send the following object (list H) to the TechRepublic Message Queue ):

Network Management Alliance www.bitsCN.com

List of www.bitsCN.com

[Serializable ()] 54ne.com

PublicclassMessageContent feedom.net

{China Network Management Forum bbs.bitsCN.com

PrivateDateTime _ creationDate = DateTime. Now;

Network Management Alliance www.bitsCN.com

Privatestring _ messageText; 54ne.com

Public MessageContent () Network Management Network bitsCN_com

{Network Management Network bitsCN.com

}

54ne.com

Public MessageContent (string messageText)

54ne.com

{

China Network Management Forum bbs.bitsCN.com

_ MessageText = messageText; 54com.cn

}

China Network Management Alliance www_bitscn_com

Publicstring MessageText

China Network Management Alliance www, bitsCN, com

{Network Management Alliance www.bitsCN.com

Get {return _ messageText ;}

China Network Management Alliance www, bitsCN, com

Set {_ messageText = value ;}

Feedom.net

} 54ne.com

PublicDateTime CreationDate: www.bitsCN.com

{

Www.bitscn.com

Get {return _ creationDate;} feedom.net

Set {_ creationDate = value;} 54com.cn

} China Network Management Alliance www, bitsCN, com

} Network Management Network bitsCN_com

Network Management Network bitsCN.com

An instance that sends this object to the queue simply calls the MessageQueue. Send method and submits an object instance as a parameter to this method. List I illustrates this situation.

List I

China Network Management Alliance www_bitscn_com

MessageContent message = newMessageContent ("Hello world! "); 54ne.com

Queue. Send (message, "Sample Message"); www.bitsCN.com

Network Management Alliance www.bitsCN.com

As you can see, the above Code is similar to the code used when we send a message whose body is a string. It is more difficult to receive messages containing serialized objects. We need to tell the message which object it contains. Network Management Network bitsCN_com

To indicate which object the message contains, we must create a formatter for the message ). Specify a System. Messaging. XmlMessageFormatter object for the message Formatter attribute to create a Formatter. Because our message contains a MessageContent object, we want to configure XmlMessageFormatter for it.

Message. Formatter = new System. Messaging. XmlMessageFormatter (54ne.com

NewType [1] {typeof (MessageContent)} China Network Management Alliance www_bitscn_com

); China Network Management Alliance www, bitsCN, com

Network Management Alliance www.bitsCN.com

Now that we have specified a Formatter for the message, we can extract the MessageContent object from the message. However, before that, we need to allocate the return value of the message. Body attribute to a MessageContent object.

China Network Management Alliance www, bitsCN, com

List K network management Alliance www.bitsCN.com

MessageContent content = (MessageContent) message. Body;

54com.cn

In this example, the "content" variable is the serialized version of the original MessageContent object we send to the queue. We can access all attributes and values of the original object.

Feedom.net

Set message priorityChina Network Management Alliance www_bitscn_com

Normally, messages in the queue are accessed in the first-in-first-out form. This indicates how to first send message A and then send message B. Then, the queue will first return message A and then message B. In most cases, there is no problem. However, sometimes, because a message is more important than other messages, you want to put it before the queue. To implement this function, you need to set the message priority level.

China Network Management Alliance www_bitscn_com

The Priority of a Message is determined by its Message. Priority attribute value. The following lists all valid values of this attribute (all from the list type of MessagePriority ):

China Network Management Alliance www, bitsCN, com

· Highest (Highest)

China Network Management Alliance www_bitscn_com

· Very high (VeryHigh)

Www.bitscn.com

· High)

China Network Management Alliance www, bitsCN, com

· Higher than normal (AboveNormal)

Network Management Alliance www.bitsCN.com

· Normal China Network Management Forum bbs.bitsCN.com

· Low (Low) Network Management Network bitsCN.com

· Very low (VeryLow)

Network Management Network bitsCN_com

· Lowest (Lowest)

China Network Management Forum bbs.bitsCN.com

Www.bitscn.com

The priority of a message in the queue is determined by its priority. For example, if there are four messages in the queue, the priority of the two messages is Normal ), the other two values are "High ). Messages in the queue are arranged as follows:

· High Priority A -- this is the first "High" Priority message sent to the queue.

54com.cn

· High Priority B -- this is the second "High" Priority message sent to the queue. Network Management Network bitsCN_com

· Normal Priority A -- this is the first "Normal" Priority message in the sending queue.

Www.bitscn.com

· Normal Priority B -- this is the second "Normal" Priority message of the sending queue.

Network Management Alliance www.bitsCN.com

In this order, if we send another "highest" Priority message to the queue, it will be at the top of the queue.

China Network Management Alliance www, bitsCN, com

To use the message priority function, you must modify the message sending code. Because the Message object constructor does not specify the Message priority, you must instantiate a Message object and set the corresponding attributes for it before sending it to the queue. The code in list L shows how to set priority and send a "highest" message to the queue. Feedom.net

List L

Network Management Alliance www.bitsCN.com

// Instantiate the queue China Network Management Alliance www.bitscn.com

MessageQueue queue = newMessageQueue (queueName );

Www.bitscn.com

// Create a XmlSerializer for the object type we're re sending.

Network Management Alliance www.bitsCN.com

XmlSerializer serializer = new China Network Management Alliance www_bitscn_com

XmlSerializer (typeof (MessageContent ));

54com.cn

// Instantiate a new message.

Network Management Network bitsCN_com

System. Messaging. Message queueMessage =

Www.bitscn.com

New System. Messaging. Message ();

China Network Management Alliance www, bitsCN, com

// Set the priority to Highest.

China Network Management Alliance www_bitscn_com

QueueMessage. Priority = MessagePriority. Highest; www.bitsCN.com

// Create our MessageContent object.

Feedom.net

MessageContent messageContent = China Network Management Alliance www, bitsCN, com

NewMessageContent ("Hello world-IMPORTANT! "); Feedom.net

// Serialize the MessageContent object into the queueMessage. China Network Management Alliance www, bitsCN, com

Serializer. Serialize (queueMessage. BodyStream, messageContent); 54com.cn

// Send the message.

China Network Management Alliance www_bitscn_com

Queue. Send (queueMessage, "high priority"); 54ne.com

China Network Management Alliance www, bitsCN, com

The most obvious difference between this code and the above Code is that it uses XmlFormatter. It is optional. The code in list L can also be replaced by the code in list M.

China Network Management Forum bbs.bitsCN.com

List M

Network Management Network bitsCN_com

// Instantiate a new message. feedom.net

System. Messaging. Message queueMessage = 54com.cn

New System. Messaging. Message (); China Network Management Forum bbs.bitsCN.com

// Set the priority to Highest. www.bitscn.com

QueueMessage. Priority = MessagePriority. Highest;

Network Management Alliance www.bitsCN.com

// Create our MessageContent object. www.bitscn.com

MessageContent messageContent = 54ne.com

NewMessageContent ("Hello world-IMPORTANT! "); China Network Management Forum bbs.bitsCN.com

// Set the body as the messageContent object. China Network Management Alliance www, bitsCN, com

QueueMessage. Body = messageContent; Network Management Network bitsCN.com

// Send the message.

Network Management Network bitsCN_com

Queue. Send (queueMessage, "high priority"); 54com.cn

China Network Management Forum bbs.bitsCN.com

This code executes the same task as the code in list L, but the code is less. Network Management Network bitsCN.com

Application

Network Management Network bitsCN.com

The input consumer request is a simple instance of the MSMQ function. The consumer sends a request to the Message Queue by a consumer-oriented application. After a request is sent to the queue, it sends a confirmation (acknowledgement) to the consumer ).

China Network Management Forum bbs.bitsCN.com

Then, an independent process extracts messages from the queue and runs any required business logic ). After the business logic is completed, the processing system submits a response to another queue. Next, the consumer-oriented application extracts the response from the queue and returns a response to the consumer.

Network Management Network bitsCN.com

This type of configuration can accelerate the speed of consumer-oriented applications, so that they can quickly respond, while doing a lot of processing in an internal system. In this way, the request processing can be distributed across multiple internal machines to provide scalability.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.