SoFunction
Updated on 2025-03-07

How to use MSMQ in C#

MSMQ (Microsoft Message Queue) is the message queue that is available by default in Windows. As a reliable way to send and receive messages across computer systems, MSMQ provides a scalable, thread-safe, simple and easy to use queue, while providing you with the opportunity to persist messages in a Windows database. MSDN notes: "Message Queuing (MSMQ) technology enables applications running at different times to communicate between heterogeneous networks and systems that may be temporarily offline. Applications send messages to and read messages from the queue."

When using MSMQ, there are usually two different applications - sender and receiver. When messages are sent by the sender, the receiver application does not need to be in an execution state—the messages are actually stored in a queue maintained by the host operating system, and when the receiver application needs them, these messages are out of the queue.

Create a queue

You can open MSMQ in your system through the “Open or Turn Windows Features” option on the Control Panel. After installing MSMQ in the system, creating a queue is very 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 Queue node. You can also create queues programmatically.

MSMQ in C#

To use MSMQ, you need to introduce a namespace. To create a queue programmatically, you need to use the Create method of the MessageQueue class. The following code snippet illustrates this.

(@".\Private$\IDG");

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

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

Now, suppose you want to check if the queue exists, and if so, send a message to it. If the queue does not exist, you may want to create a new queue and then send a message to it. This is exactly what the following code list does.

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 ((path))
    {
      messageQueue = new MessageQueue(path);
       = description;
    }
    else
    {
      (path);
      messageQueue = new MessageQueue(path);
       = description;
    }
    (message);
  }
  catch
  {
    throw;
  }
  finally
  {
    ();
  }
}

The following code list demonstrates how to use C# to process messages stored in a message queue.

private static List<string> ReadQueue(string path)
{
  List<string> lstMessages = new List<string>();
  using (MessageQueue messageQueue = new MessageQueue(path))
  {
    [] messages = ();
    foreach ( message in messages)
    {
       = new XmlMessageFormatter(
      new String[] { ", mscorlib" });
      string msg = ();
      (msg);
    }
  }
  return lstMessages;
}

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

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

You can also store objects in the message queue. For example, suppose you need to store log messages into a queue. Log messages are stored in an instance of the LogMessage class that contains necessary properties related to the details of the log message. Below is the LogMessage class - I only used two properties to make it simple.

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

You should modify the LogMessage class to include other necessary properties, such as message severity, etc. The following method illustrates how to store an instance of the LogMessage class into a message queue.

private static void SendMessage(string queueName, LogMessage msg)
{
  MessageQueue messageQueue = null;
  if (!(queueName))
    messageQueue = (queueName);
  else
    messageQueue = new MessageQueue(queueName);
  try
  {
     = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });
    (msg);
  }
  catch
  {
    //Write code here to do the necessary error handling.
  }
  finally
  {
    ();
  }
}

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

LogMessage msg = new LogMessage()
{
  MessageText = "This is a test message.",
  MessageTime = 
};
SendMessage(@".\Private$\IDGLog", msg);

The following code list demonstrates how to read a LogMessage instance stored in a message queue.

private static LogMessage ReceiveMessage(string queueName)
{
  if (!(queueName))
    return null;
  MessageQueue messageQueue = new MessageQueue(queueName);
  LogMessage logMessage = null;
  try
  {
     = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });
    logMessage = (LogMessage)().Body;
  }
  catch { }
  finally
  {
    ();
  }
  return logMessage;
}

The above is the detailed content of the method of using MSMQ in C#. For more information about using msmq in c#, please follow my other related articles!