Skip to main content

MSMQ is a persistent backing store for storing messages. Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline. Applications send messages to queues and read messages from queues. The following illustration shows how a queue can hold messages that are generated by multiple sending applications and read by multiple receiving applications.

---
title: How to work with MSMQ in C#
subtitle: MSMQ persistent backing store for storing messages
author: Joydip Kanjilal
date: April 21, 2016
source: https://www.infoworld.com/article/3060115/how-to-work-with-msmq-in-c.html
notoc: false
---

## Intro

MSMQ (Microsoft Message Queuing) is a message queue that is available by
default as part of Windows. A reliable way of sending and receiving
messages across computer systems, MSMQ provides a queue that\'s
scalable, thread-safe, simple, and convenient to use while at the same
time providing you the opportunity to persist the messages inside the
Windows database. [The MSDN states](https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx):

> *Message Queuing (MSMQ) technology enables applications running at different
> times to communicate across heterogeneous networks and systems that may be
> temporarily offline. Applications send messages to queues and read messages
> from queues.*

Typically, you have two distinct applications when working with MSMQ --
the sender and the receiver. When the messages are sent by the sender,
i.e., the sending application, the receiving application need not be in
execution state -- the messages are actually stored in a queue
maintained by the host operating system and these are de-queued as and
when they are needed by the receiving application.

## Creating a Queue

You can turn on MSMQ in your system through the \"Turn Windows features
on or off\" option from the control panel. Once MSMQ has been installed
in your system, creating a queue is simple. Just go to \"My Computer\",
right click and select Manage. In the \"Computer Management\" window you
can create a new queue from the \"Message Queuing\" node. You can also
create a queue programmatically.

## Programming MSMQ in C\#

To work with MSMQ, you would need to include the System.Messaging
namespace. To create a queue programmatically, you need to leverage the
Create method of the MessageQueue class. The following code snippet
illustrates this.

```cs
MessageQueue.Create(@".\Private$\IDG");
```

To create a queue and send a message to it, you can use the following
code snippet.

```cs
MessageQueue.Create(@".\Private$\IDG");

messageQueue = new MessageQueue(@".\Private$\IDG");
messageQueue.Label = "This is a test queue.";
messageQueue.Send("This is a test message.", "IDG");
```

Now, suppose you would like to check if the queue exists and if it does, send a
message to it. If the queue doesn't exist, you may want to create a new one and
then send it a message. This is exactly what the following code listing does for
you.

```cs
static void Main(string[] args)
{
    MessageQueue messageQueue = null;

    string description = "This is a test queue.";
    string message = "This is a test message.";
    string path = @".\Private$\IDG";

    try
    {
        if (MessageQueue.Exists(path))
        {
            messageQueue = new MessageQueue(path);
            messageQueue.Label = description;
        }
        else
        {
            MessageQueue.Create(path);
            messageQueue = new MessageQueue(path);
            messageQueue.Label = description;
        }

        messageQueue.Send(message);
    }
    catch
    {
        throw;
    }
    finally
    {
        messageQueue.Dispose();
    }
}
```

The following code listing illustrates how you can process the messages
stored in a message queue using C\#.

```cs
private static List<string> ReadQueue(string path)
{
    List<string> lstMessages = new List<string>();

    using(MessageQueue messageQueue = new MessageQueue(path))
    {
        System.Messaging.Message[] messages = messageQueue.GetAllMessages();

        foreach (System.Messaging.Message message in messages)
        {
            message.Formatter = new XmlMessageFormatter(
                new String[] { "System.String, mscorlib" });

            string msg = message.Body.ToString();

            lstMessages.Add(msg);
        }
    }

    return lstMessages;
}
```

Next, you can invoke the ReadQueue method to retrieve the messages
stored in the message queue as shown in the code snippet below.

```cs
string path = @".\Private$\IDG";
List<string> lstMessages = ReadQueue(path);
```

You can also store objects in the message queue. As an example, suppose you need
to store a log message to the queue. The log message is stored in an instance of
the LogMessage class that contains the necessary properties that pertain to the
details of the log message. Here's how the LogMessage class would look like --
I've made it simple with just two properties only.

```cs
public class LogMessage
{
    public string MessageText { get; set; }
    public DateTime MessageTime { get; set; }
}
```

You should modify the LogMessage class to incorporate other necessary
properties, i.e., message severity, etc. The following method
illustrates how you can store an instance of the LogMessage class to the
message queue.

```cs
private static void SendMessage(string queueName, LogMessage msg)
{
    MessageQueue messageQueue = null;

    if (!MessageQueue.Exists(queueName))
    {
        messageQueue = MessageQueue.Create(queueName);
    }
    else
    {
        messageQueue = new MessageQueue(queueName);
    }

    try
    {
        messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });
        messageQueue.Send(msg);
    }
    catch
    {
        // Write code here to do the necessary error handling...
    }
    finally
    {
        messageQueue.Close();
    }
}
```

The following code snippet illustrates how you can create an instance of
the LogMessage class, populate it with data and then invoke the
SendMessage method to store the instance created in the message queue.

```cs
var msg = new LogMessage
{
    MessageText = "This is a test message.",
    MessageTime = DateTime.Now
};

SendMessage(@".\Private$\IDGLog", msg);
```

The following code listing illustrates how you can read the LogMessage
instance stored in the message queue.

```cs
private static LogMessage ReceiveMessage(string queueName)
{
    if (!MessageQueue.Exists(queueName))
    {
        return null;
    }

    MessageQueue messageQueue = new MessageQueue(queueName);
    LogMessage logMessage = null;

    try
    {
        messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });
        logMessage = (LogMessage)messageQueue.Receive().Body;
    }
    catch {}
    finally
    {
        messageQueue.Close();
    }

    return logMessage;
}
```