MessageQueue.Peek Method

Definition

Returns a copy of the first message in the queue without removing the message from the queue.

Overloads

Peek()

Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek() method is synchronous, so it blocks the current thread until a message becomes available.

Peek(TimeSpan)

Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek() method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.

Peek(TimeSpan, Cursor, PeekAction)

Returns without removing (peeks) the current or next message in the queue, using the specified cursor. The Peek() method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.

Peek()

Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek() method is synchronous, so it blocks the current thread until a message becomes available.

C#
public System.Messaging.Message Peek();

Returns

The Message that represents the first message in the queue.

Exceptions

An error occurred when accessing a Message Queuing method.

Examples

The following examples use the Peek method on a queue.

In the first example, the application waits until a message becomes available in the queue. Note that the first example does not access the message that arrives; it merely pauses processing until a message arrives. If a message already exists in the queue, it will return immediately.

In the second example, a message that contains an application-defined Order class is sent to the queue, and then peeked from the queue.

C#
using System;
using System.Messaging;

namespace MyProject
{

    // This class represents an object the following example
    // sends to a queue and receives from a queue.
    public class Order
    {
        public int orderId;
        public DateTime orderTime;
    };	

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

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example posts a notification that a message
        // has arrived in a queue. It sends a message
        // containing an other to a separate queue, and then
        // peeks the first message in the queue.
        //**************************************************

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

            // Wait for a message to arrive in the queue.
            myNewQueue.NotifyArrived();

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

            // Peek the first message in the queue.
            myNewQueue.PeekFirstMessage();
                        
            return;
        }

        //**************************************************
        // Posts a notification when a message arrives in
        // the queue "monitoredQueue". Does not retrieve any
        // message information when peeking the message.
        //**************************************************
        
        public void NotifyArrived()
        {

            // Connect to a queue.
            MessageQueue myQueue = new
                MessageQueue(".\\monitoredQueue");
    
            // Specify to retrieve no message information.
            myQueue.MessageReadPropertyFilter.ClearAll();

            // Wait for a message to arrive.
            Message emptyMessage = myQueue.Peek();

            // Post a notification when a message arrives.
            Console.WriteLine("A message has arrived in the queue.");

            return;
        }

        //**************************************************
        // Sends an Order to a queue.
        //**************************************************
        
        public void SendMessage()
        {
            
            // Create a new order and set values.
            Order sentOrder = new Order();
            sentOrder.orderId = 3;
            sentOrder.orderTime = DateTime.Now;

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

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

            return;
        }

        //**************************************************
        // Peeks a message containing an Order.
        //**************************************************
        
        public void PeekFirstMessage()
        {
            // Connect to a queue.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");
    
            // Set the formatter to indicate the body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(MyProject.Order)});
            
            try
            {
                // Peek and format the message.
                Message myMessage =	myQueue.Peek();
                Order myOrder = (Order)myMessage.Body;

                // Display message information.
                Console.WriteLine("Order ID: " +
                    myOrder.orderId.ToString());
                Console.WriteLine("Sent: " +
                    myOrder.orderTime.ToString());
            }
            
            catch (MessageQueueException)
            {
                // Handle Message Queuing exceptions.
            }

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

            return;
        }
    }
}

Remarks

Use this overload to peek a queue, or to wait until a message exists in the queue.

The Peek method reads, but does not remove, the first message from the queue. Therefore, repeated calls to Peek return the same message, unless a higher priority message arrives in the queue. The Receive method, on the other hand, both reads and removes the first message from the queue. Repeated calls to Receive, therefore, return different messages.

Message Queuing orders messages in the queue according to priority and arrival time. A newer message is placed before an older one only if it is of a higher priority.

Use Peek when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. Because this overload does not specify a time-out, the application might wait indefinitely. If you need the application processing to continue without waiting, use the asynchronous BeginPeek method. Alternatively, you can specify a time-out for a message to arrive in the queue by using the overload of Peek that specifies a time-out.

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

Peek(TimeSpan)

Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek() method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.

C#
public System.Messaging.Message Peek(TimeSpan timeout);

Parameters

timeout
TimeSpan

A TimeSpan that indicates the maximum time to wait for the queue to contain a message.

Returns

The Message that represents the first message in the queue.

Exceptions

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

An error occurred when accessing a Message Queuing method.

Examples

The following code example uses the Peek method with a time-out of zero to check whether the queue is empty.

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 determines whether a queue is empty.
        //**************************************************

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

            // Determine whether a queue is empty.
            bool isQueueEmpty = myNewQueue.IsQueueEmpty();
                        
            return;
        }

        //**************************************************
        // Determines whether a queue is empty. The Peek()
        // method throws an exception if there is no message
        // in the queue. This method handles that exception
        // by returning true to the calling method.
        //**************************************************
        
        public bool IsQueueEmpty()
        {
            bool isQueueEmpty = false;

            // Connect to a queue.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            try
            {
                // Set Peek to return immediately.
                myQueue.Peek(new TimeSpan(0));

                // If an IOTimeout was not thrown, there is a message
                // in the queue.
                isQueueEmpty = false;
            }

            catch(MessageQueueException e)
            {
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    // No message was in the queue.
                    isQueueEmpty = true;
                }

                // Handle other sources of MessageQueueException.
            }

            // Handle other exceptions as necessary.

            // Return true if there are no messages in the queue.
            return isQueueEmpty;
        }
    }
}

Remarks

Use this overload to peek a queue, or to wait a specified period of time until a message exists in the queue. The method returns immediately if a message already exists in the queue.

The Peek method reads, but does not remove, the first message from the queue. Therefore, repeated calls to Peek return the same message, unless a higher priority message arrives in the queue. The Receive method, on the other hand, both reads and removes the first message from the queue. Repeated calls to Receive, therefore, return different messages.

Message Queuing orders messages in the queue according to priority and arrival time. A newer message is placed before an older one only if it is of a higher priority.

Use Peek when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. The thread will be blocked up to the specified period of time, or indefinitely if you indicated InfiniteTimeout. If you need the application processing to continue without waiting, use the asynchronous BeginPeek method.

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

Peek(TimeSpan, Cursor, PeekAction)

Returns without removing (peeks) the current or next message in the queue, using the specified cursor. The Peek() method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.

C#
public System.Messaging.Message Peek(TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.PeekAction action);

Parameters

timeout
TimeSpan

A TimeSpan that indicates the maximum time to wait for the queue to contain a message.

cursor
Cursor

A Cursor that maintains a specific position in the message queue.

action
PeekAction

One of the PeekAction values. Indicates whether to peek at the current message in the queue, or the next message.

Returns

A Message that represents a message in the queue.

Exceptions

A value other than PeekAction.Current or PeekAction.Next was specified for the action parameter.

The cursor parameter is null.

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

An error occurred when accessing a Message Queuing method.

Remarks

Use this overload to peek a queue, or to wait a specified period of time until a message exists in the queue. The method returns immediately if a message already exists in the queue.

The Peek method reads, but does not remove, a message from the queue. The Receive method, on the other hand, both reads and removes a message from the queue.

Use Peek when it is acceptable for the current thread to be blocked while it waits for a message to arrive in the queue. The thread is blocked up to the specified period of time, or indefinitely if you indicated InfiniteTimeout. If you need the application processing to continue without waiting, use the asynchronous BeginPeek method.

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 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

Thread Safety

The method is not thread safe.