public MessageContent(string messageText) { _messageText = messageText; }
publicstring MessageText { get { return _messageText; } set { _messageText = value; } }
public DateTime CreationDate { get { return _creationDate; } set { _creationDate = value; } } }
然后创建一个消息队列
privatevoid CreateQueue() ...{ //Does the queue already exist if (MessageQueue.Exists(queueName1)) //Yes, it's already there. queue =new MessageQueue(queueName1); else //No, we need to create it. queue = MessageQueue.Create(queueName1, false); }
发送消息
privatevoid btnSendMessage_Click(object sender, EventArgs e) ...{ //Instantiate our MessageContent object. MessageContent message =new MessageContent("Hello world!"); //Send it to the queue. queue.Send(message, "Sample Message"); MessageBox.Show("Message sent.", "MSMQ"); }
列举所有消息体
privatevoid btnEnumerateMessages_Click(object sender, EventArgs e) ...{ //Clear the textbox. this.txtMessages.Clear(); //Get all messages on the queue. System.Messaging.Message[] messages = queue.GetAllMessages(); //Loop through the messages. foreach (System.Messaging.Message message in messages) ...{ //Set the formatter for the message. message.Formatter =new System.Messaging.XmlMessageFormatter(new Type[1] ...{ typeof(MessageContent) }); //Get the MessageContent object out of the message. MessageContent content = (MessageContent)message.Body; //Update the textbox. this.txtMessages.Text += content.MessageText +" - "+ content.CreationDate.ToString() +""; } }
移除消息
privatevoid btnRemoveMessages_Click(object sender, EventArgs e) ...{ //Purge all messages from the queue. queue.Purge(); MessageBox.Show("Messages purged", "MSMQ"); }
设置消息优先级
privatevoid btnSendHighestPriorityMessage_Click(object sender, EventArgs e) ...{ //Create a XmlSerializer for the object type we're sending. XmlSerializer serializer =new XmlSerializer(typeof(MessageContent)); //Instantiate a new message. System.Messaging.Message queueMessage =new System.Messaging.Message(); //Set the priority to Highest. queueMessage.Priority = MessagePriority.Highest; //Create our MessageContent object. MessageContent messageContent =new MessageContent("Hello world - IMPORTANT!"); //Serialize the MessageContent object into the queueMessage. serializer.Serialize(queueMessage.BodyStream, messageContent); //Send the message. queue.Send(queueMessage, "HIGH PRIORITY"); MessageBox.Show("Important message sent.", "MSMQ"); }