Friday, July 17, 2015

MSMQ - Bare minimum example

Sometimes you need a project to be split into two programs but still pass data between eachother. A normal way of doing this would be with a webserver, like a WCF service.
There is however a simpler way of achieving this functionality, using a windows preinstalled component called MSMQ.

MSMQ is a message queue system. An application can push messages to a queue and another application can read them out. MSMQ also has the advantage of keeping queue messages even if a client goes offline. The messages can then be retrieved the next time the client comes online.

The code:
This first code snippet initializes the queue:
public static MessageQueue mq;
private void btnInitQueue_Click(object sender, EventArgs e)
{
 // Create queue or connect to an existing queue
 if (MessageQueue.Exists(@".\Private$\MyQueue"))
 {
  mq = new MessageQueue(@".\Private$\MyQueue");
 }
 else
 {
  mq = MessageQueue.Create(@".\Private$\MyQueue");
 }
}

This next snippet adds a string message to the queue:
private void btnSendMessage_Click(object sender, EventArgs e)
{
 // This adds a message to the queue
 System.Messaging.Message mm = new System.Messaging.Message();
 mm.Body = textBox1.Text;
 mq.Send(mm);
}

And this last snippet is used to read out the messages from the queue:
private void btnReadOutMessages_Click(object sender, EventArgs e)
{
 // This retrieves all messages in the queue, processes them and deletes them 
 System.Messaging.Message[] messages = mq.GetAllMessages();
 foreach (System.Messaging.Message m in messages)
 {
  // Need to read the messages with a formatter
  m.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
  richTextBox1.AppendText(m.Body.ToString());
 }
 mq.Purge();
}

Notice we need to apply a formatter when reading data out from the queue.

No comments:

Post a Comment