This documentation is archived and is not being maintained.

MessageQueue.Receive Method (TimeSpan)

.NET Framework 1.1

Receives the first message available in the queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.

[Visual Basic]
Overloads Public Function Receive( _
   ByVal timeout As TimeSpan _
) As Message
[C#]
public Message Receive(
 TimeSpan timeout
);
[C++]
public: Message* Receive(
 TimeSpan timeout
);
[JScript]
public function Receive(
   timeout : TimeSpan
) : Message;

Parameters

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

Return Value

A Message that references the first message available in the queue.

Exceptions

Exception Type Condition
ArgumentException The value specified for the timeout parameter is invalid, possibly timeout is less than TimeSpan.Zero or greater than TimeSpan.MaxValue.
MessageQueueException A message did not arrive in the queue before the time-out expired.

-or-

An error occurred when accessing a Message Queuing API

Remarks

Use this overload to receive a message and return in a specified period of time if there are no messages in the queue.

The Receive method allows for the synchronous reading of a message, removing it from the queue. Subsequent calls to Receive will return the messages that follow in the queue, or new, higher priority messages.

To read the first message in a queue without removing it from the queue, use the Peek method. The Peek method always returns the first message in the queue, so subsequent calls to the method return the same message unless a higher priority message arrives in the queue.

Use a call to Receive 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 for the given period of time, or indefinitely if you specified the value InfiniteTimeout for the timeout parameter. If the application processing should continue without waiting for a message, consider using the asynchronous method, BeginReceive.

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

Workgroup Mode Available
Local computer Yes
Local computer + direct format name Yes
Remote computer No
Remote computer + direct format name Yes

Example

[Visual Basic, C#, C++] The following example receives a message from a queue and outputs information about that message to the screen. The example pauses execution for up to five seconds while waiting for a message to arrive in the queue.

[Visual Basic] 
Imports System
Imports System.Messaging

Namespace MyProject

    ' This class represents an object the following example 
    ' receives from a queue.
    Public Class Order
        Public orderId As Integer
        Public orderTime As DateTime
    End Class 'Order


    '/ <summary>
    '/ Provides a container class for the example.
    '/ </summary>
    Public Class MyNewQueue


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

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue()

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessage()

            Return

        End Sub 'Main


        '**************************************************
        ' Receives a message containing an Order.
        '**************************************************

        Public Sub ReceiveMessage()

            ' Connect to the a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")

            ' Set the formatter to indicate body contains an Order.
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType(MyProject.Order)})

            Try

                ' Receive and format the message. 
                ' Wait 5 seconds for a message to arrive.
                Dim myMessage As Message = myQueue.Receive(New _
                    TimeSpan(0, 0, 5))
                Dim myOrder As Order = CType(myMessage.Body, Order)

                ' Display message information.
                Console.WriteLine(("Order ID: " + _
                    myOrder.orderId.ToString()))
                Console.WriteLine(("Sent: " + _
                    myOrder.orderTime.ToString()))

            Catch e As MessageQueueException
                ' Handle no message arriving in the queue.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.IOTimeout Then

                    Console.WriteLine("No message arrived in queue.")

                End If

                ' Handle other sources of a MessageQueueException.

            Catch e As InvalidOperationException
                ' Handle invalid serialization format.
                Console.WriteLine(e.Message)

                ' Catch other exceptions as necessary.

            End Try

            Return

        End Sub 'ReceiveMessage

    End Class 'MyNewQueue
End Namespace 'MyProject

[C#] 
using System;
using System.Messaging;

namespace MyProject
{
    // This class represents an object the following example 
    // 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 receives a message from a queue.
        //**************************************************

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

            // Receive a message from a queue.
            myNewQueue.ReceiveMessage();

            return;
        }


        //**************************************************
        // Receives a message containing an Order.
        //**************************************************

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

            // Set the formatter to indicate body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(MyProject.Order)});
            
            try
            {
                // Receive and format the message. 
                // Wait 5 seconds for a message to arrive.
                Message myMessage =    myQueue.Receive(new 
                    TimeSpan(0,0,5)); 
                Order myOrder = (Order)myMessage.Body;

                // Display message information.
                Console.WriteLine("Order ID: " + 
                    myOrder.orderId.ToString());
                Console.WriteLine("Sent: " + 
                    myOrder.orderTime.ToString());
            }

            catch (MessageQueueException e)
            {
                // Handle no message arriving in the queue.
                if (e.MessageQueueErrorCode == 
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine("No message arrived in queue.");
                }            

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

            return;
        }
    }
}

[C++] 
#using <mscorlib.dll>
#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;

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

/// <summary>
/// Provides a container class for the example.
/// </summary>
__gc class MyNewQueue 
{
public:
    //*************************************************
    // Receives a message containing an Order.
    //*************************************************
    void ReceiveMessage() 
    {
        // Connect to the a queue on the local computer.
        MessageQueue* myQueue = new MessageQueue(S".\\myQueue");

        // Set the formatter to indicate body contains an Order.
        Type* p __gc[] = new Type* __gc[1];
        p[0] = __typeof(Order);
        myQueue->Formatter = new XmlMessageFormatter( p );

        try 
        {
            // Receive and format the message. 
            // Wait 5 seconds for a message to arrive.
            Message* myMessage = myQueue->Receive(TimeSpan(0, 0, 5)); 
            Order* myOrder = static_cast<Order*>(myMessage->Body);

            // Display message information.
            Console::WriteLine(S"Order ID: {0}", __box(myOrder->orderId));
            Console::WriteLine(S"Sent: {0}", __box(myOrder->orderTime));
        }
        catch (MessageQueueException* e) 
        {
            // Handle no message arriving in the queue.
            if (e->MessageQueueErrorCode == 
                MessageQueueErrorCode::IOTimeout) 
            {
                Console::WriteLine(S"No message arrived in queue.");
            }            

            // Handle other sources of a MessageQueueException.
        }

        // Handle invalid serialization format.
        catch (InvalidOperationException* e) 
        {
            Console::WriteLine(e->Message);
        }

        // Catch other exceptions as necessary.

        return;
    }
};

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

int main() 
{
    // Create a new instance of the class.
    MyNewQueue* myNewQueue = new MyNewQueue();

    // Receive a message from a queue.
    myNewQueue->ReceiveMessage();

    return 0;
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

.NET Framework Security: 

See Also

MessageQueue Class | MessageQueue Members | System.Messaging Namespace | MessageQueue.Receive Overload List | InfiniteTimeout | ReceiveById | ReceiveByCorrelationId | Peek | BeginReceive

Show: