MessageQueue.PeekByCorrelationId Method

Definition

Peeks a message that matches a given correlation identifier.

Overloads

PeekByCorrelationId(String)

Peeks the message that matches the given correlation identifier and immediately raises an exception if no message with the specified correlation identifier currently exists in the queue.

PeekByCorrelationId(String, TimeSpan)

Peeks the message that matches the given correlation identifier and waits until either a message with the specified correlation identifier is available in the queue, or the time-out expires.

PeekByCorrelationId(String)

Peeks the message that matches the given correlation identifier and immediately raises an exception if no message with the specified correlation identifier currently exists in the queue.

C#
public System.Messaging.Message PeekByCorrelationId(string correlationId);

Parameters

correlationId
String

The CorrelationId of the message to peek.

Returns

The Message whose CorrelationId matches the correlationId parameter passed in.

Exceptions

The correlationId parameter is null.

The message with the specified correlationId could not be found.

An error occurred when accessing a Message Queuing method.

Examples

The following code example sends and receives a message that contains an order to and from a queue. It specifically requests a positive acknowledgment when the original message reaches or is retrieved from the queue.

C#
using System;
using System.Messaging;

namespace MyProject
{

    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue
    {

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example sends and receives a message from
        // a queue.
        //**************************************************

        public static void Main()
        {
            // Create a new instance of the class.
            MyNewQueue myNewQueue = new MyNewQueue();

            // Create new queues.
            CreateQueue(".\\myQueue");
            CreateQueue(".\\myAdministrationQueue");

            // Send messages to a queue.
            myNewQueue.SendMessage();

            // Receive messages from a queue.
            string messageId = myNewQueue.ReceiveMessage();

            // Receive acknowledgment message.
            if(messageId != null)
            {
                myNewQueue.ReceiveAcknowledgment(messageId, ".\\myAdministrationQueue");
            }

            return;
        }

        //**************************************************
        // Creates a new queue.
        //**************************************************

        public static void CreateQueue(string queuePath)
        {
            try	
            {
                if(!MessageQueue.Exists(queuePath))
                {
                    MessageQueue.Create(queuePath);
                }
                else
                {
                    Console.WriteLine(queuePath + " already exists.");
                }
            }
            catch (MessageQueueException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        //**************************************************
        // Sends a string message to a queue.
        //**************************************************
        
        public void SendMessage()
        {

            // Connect to a queue on the local computer.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            // Create a new message.
            Message myMessage = new Message("Original Message");

            myMessage.AdministrationQueue = new MessageQueue(".\\myAdministrationQueue");
            myMessage.AcknowledgeType = AcknowledgeTypes.PositiveReceive | AcknowledgeTypes.PositiveArrival;

            // Send the Order to the queue.
            myQueue.Send(myMessage);

            return;
        }

        //**************************************************
        // Receives a message containing an Order.
        //**************************************************
        
        public  string ReceiveMessage()
        {
            // Connect to the a queue on the local computer.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            myQueue.MessageReadPropertyFilter.CorrelationId = true;

            // Set the formatter to indicate body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(string)});

            string returnString = null;
            
            try
            {
                // Receive and format the message.
                Message myMessage =	myQueue.Receive();

                // Display message information.
                Console.WriteLine("____________________________________________");
                Console.WriteLine("Original message information--");
                Console.WriteLine("Body: " +myMessage.Body.ToString());
                Console.WriteLine("Id: " + myMessage.Id.ToString());
                Console.WriteLine("____________________________________________");

                returnString =  myMessage.Id;
            }
            
            catch (MessageQueueException)
            {
                // Handle Message Queuing exceptions.
            }

            // Handle invalid serialization format.
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            
            // Catch other exceptions as necessary.

            return returnString;
        }

        //**************************************************
        // Receives a message containing an Order.
        //**************************************************
        
        public void ReceiveAcknowledgment(string messageId, string queuePath)
        {
            bool found = false;
            MessageQueue queue = new MessageQueue(queuePath);
            queue.MessageReadPropertyFilter.CorrelationId = true;
            queue.MessageReadPropertyFilter.Acknowledgment = true;

            try
            {
                while(queue.PeekByCorrelationId(messageId) != null)
                {
                    Message myAcknowledgmentMessage = queue.ReceiveByCorrelationId(messageId);
            
                    // Output acknowledgment message information. The correlation Id is identical
                    // to the id of the original message.
                    Console.WriteLine("Acknowledgment Message Information--");
                    Console.WriteLine("Correlation Id: " + myAcknowledgmentMessage.CorrelationId.ToString());
                    Console.WriteLine("Id: " + myAcknowledgmentMessage.Id.ToString());
                    Console.WriteLine("Acknowledgment Type: " + myAcknowledgmentMessage.Acknowledgment.ToString());
                    Console.WriteLine("____________________________________________");

                    found = true;
                }
            }
            catch (InvalidOperationException e)
            {
                // This exception would be thrown if there is no (further) acknowledgment message
                // with the specified correlation Id. Only output a message if there are no messages;
                // not if the loop has found at least one.
                if (!found)
                {	
                    Console.WriteLine(e.Message);
                }

                // Handle other causes of invalid operation exception.
            }
        }
    }
}

Remarks

This method looks in the queue referenced by the MessageQueue for a message whose CorrelationId matches the specified correlationId parameter. If no message is found that matches the correlationID parameter, an exception is thrown.

The CorrelationId property is used to tie a message sent to the queue to associated response, report, or acknowledgment messages.

Two other methods allow you to peek messages in a queue. The Peek method returns the first message in the queue, and the PeekById(String) method is used to retrieve a message by specifying its unique identifier.

The following table shows whether this method is available in various Workgroup modes.

Workgroup mode Available
Local computer Yes
Local computer and direct format name Yes
Remote computer No
Remote computer and direct format name Yes

See also

Applies to

.NET Framework 4.8.1 and other versions
Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

PeekByCorrelationId(String, TimeSpan)

Peeks the message that matches the given correlation identifier and waits until either a message with the specified correlation identifier is available in the queue, or the time-out expires.

C#
public System.Messaging.Message PeekByCorrelationId(string correlationId, TimeSpan timeout);

Parameters

correlationId
String

The CorrelationId of the message to peek.

timeout
TimeSpan

A TimeSpan that indicates the time to wait until a new message is available for inspection.

Returns

The Message whose CorrelationId matches the correlationId parameter passed in.

Exceptions

The correlationId parameter is null.

The value specified for the timeout parameter is not valid, possibly timeout is less than Zero or greater than InfiniteTimeout.

The message with the specified correlationId does not exist in the queue and did not arrive before the time-out expired.

A message did not arrive before the time-out expired.

-or-

An error occurred when accessing a Message Queuing method.

Examples

The following code example demonstrates the use of PeekByCorrelationId(String, TimeSpan).

C#

// Connect to a queue on the local computer.
MessageQueue queue = new MessageQueue(".\\exampleQueue");

// Create a new message.
Message msg = new Message("Example Message Body");

// Designate a queue to receive the acknowledgement message for this
// message.
msg.AdministrationQueue = new MessageQueue(".\\exampleAdminQueue");

// Set the message to generate an acknowledgement message upon its
// arrival.
msg.AcknowledgeType = AcknowledgeTypes.PositiveArrival;

// Send the message.
queue.Send(msg, "Example Message Label");

// Get the message's Id property value.
string id = msg.Id;

// Receive the message from the queue.
msg = queue.ReceiveById(id, TimeSpan.FromSeconds(10.0));

// Connect to the admin queue.
MessageQueue adminQueue = new MessageQueue(".\\exampleAdminQueue");

// Set the admin queue's MessageReadPropertyFilter property to ensure
// that the acknowledgement message includes the desired properties.
adminQueue.MessageReadPropertyFilter.Acknowledgment = true;
adminQueue.MessageReadPropertyFilter.CorrelationId = true;

// Peek at the acknowledgement message.
Message ackMsg = adminQueue.PeekByCorrelationId(id,
    TimeSpan.FromSeconds(10.0));

// Display the acknowledgement message's property values.
Console.WriteLine("Message.Label: {0}", ackMsg.Label);
Console.WriteLine("Message.Acknowledgment: {0}", ackMsg.Acknowledgment);
Console.WriteLine("Message.CorrelationId: {0}", ackMsg.CorrelationId);

Remarks

This method looks in the queue referenced by the MessageQueue for a message whose CorrelationId matches the specified correlationId parameter. If no message is found that matches the correlationID parameter, and no new message arrives in the queue within the period specified by the timeout parameter, an exception is thrown.

The timeout parameter does not specify the total running time for this method. Rather, it specifies the time to wait for a new message to arrive in the queue. Each time a new message arrives, this method examines the CorrelationId of the new message to see if it matches the correlationId parameter. If not, this method starts the time-out period over and waits for another new message to arrive. Therefore, if new messages continue to arrive within the time-out period, it is possible for this method to continue running indefinitely, either until the time-out period expires without any new messages arriving, or until a message arrives whose CorrelationId matches the correlationId parameter.

The CorrelationId property is used to tie a message sent to the queue to associated response, report, or acknowledgment messages.

Two other methods allow you to peek messages in a queue. The Peek method returns the first message in the queue, and the PeekById(String) method is used to retrieve a message by specifying its unique identifier.

The following table shows whether this method is available in various Workgroup modes.

Workgroup mode Available
Local computer Yes
Local computer and direct format name Yes
Remote computer No
Remote computer and direct format name Yes

See also

Applies to

.NET Framework 4.8.1 and other versions
Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1