ערוך

שתף באמצעות


MessageQueue.BeginPeek Method

Definition

Initiates an asynchronous peek operation by telling Message Queuing to begin peeking a message and notify the event handler when finished.

Overloads

BeginPeek(TimeSpan, Object, AsyncCallback)

Initiates an asynchronous peek operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginPeek(TimeSpan, Object)

Initiates an asynchronous peek operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginPeek(TimeSpan, Cursor, PeekAction, Object, AsyncCallback)

Initiates an asynchronous peek operation that has a specified time-out and that uses a specified cursor, a specified peek action, and a specified state object. The state object provides associated information throughout the lifetime of the operation. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginPeek()

Initiates an asynchronous peek operation that has no time-out. The operation is not complete until a message becomes available in the queue.

BeginPeek(TimeSpan)

Initiates an asynchronous peek operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginPeek(TimeSpan, Object, AsyncCallback)

Initiates an asynchronous peek operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginPeek(TimeSpan timeout, System::Object ^ stateObject, AsyncCallback ^ callback);
public IAsyncResult BeginPeek (TimeSpan timeout, object stateObject, AsyncCallback callback);
member this.BeginPeek : TimeSpan * obj * AsyncCallback -> IAsyncResult
Public Function BeginPeek (timeout As TimeSpan, stateObject As Object, callback As AsyncCallback) As IAsyncResult

Parameters

timeout
TimeSpan

A TimeSpan that indicates the interval of time to wait for a message to become available.

stateObject
Object

A state object, specified by the application, that contains information associated with the asynchronous operation.

callback
AsyncCallback

The AsyncCallback that will receive the notification of the asynchronous operation completion.

Returns

The IAsyncResult that identifies the posted asynchronous request.

Exceptions

The value specified for the timeout parameter is not valid.

An error occurred when accessing a Message Queuing method.

Examples

The following code example creates an asynchronous peek operation. The code example sends a message to a local message queue, then calls BeginPeek(TimeSpan, Object, AsyncCallback), passing in: a time-out value of ten seconds; a unique integer that identifies that particular message; and a new instance of AsyncCallback that identifies the event handler, MyPeekCompleted. When a PeekCompleted event is raised, the event handler peeks at the message and writes the message body and the integer message identifier to the screen.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if(!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();      
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the PeekCompleted event.
void MyPeekCompleted(IAsyncResult^ asyncResult)
{
    // Connect to the queue.
    MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue");

    // End the asynchronous peek operation.
    Message^ msg = queue->EndPeek(asyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message number: {0}", asyncResult->AsyncState);
    Console::WriteLine("Message body: {0}", msg->Body);

    // Receive the message. This will remove the message from the queue.
    msg = queue->Receive(TimeSpan::FromSeconds(10.0));

    queue->Close();
}

int main()
{
    // Represents a state object associated with each message.
    int messageNumber = 0;

    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    CreateQueue(".\\exampleQueue", false);

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

    // Send a message to the queue.
    queue->Send("Example Message");

    // Begin the asynchronous peek operation.
    queue->BeginPeek(TimeSpan::FromSeconds(10.0), messageNumber++,
        gcnew AsyncCallback(MyPeekCompleted));

    // Simulate doing other work on the current thread.
    System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));

    queue->Close();
}
using System;
using System.Messaging;

public class QueueExample
{
    // Represents a state object associated with each message.
    static int messageNumber = 0;

    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

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

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous peek operation.
        queue.BeginPeek(TimeSpan.FromSeconds(10.0), messageNumber++,
            new AsyncCallback(MyPeekCompleted));

        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

    // Provides an event handler for the PeekCompleted event.
    private static void MyPeekCompleted(IAsyncResult asyncResult)
    {
        // Connect to the queue.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // End the asynchronous peek operation.
        Message msg = queue.EndPeek(asyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message number: {0}", (int)asyncResult.AsyncState);
        Console.WriteLine("Message body: {0}", (string)msg.Body);

        // Receive the message. This will remove the message from the queue.
        msg = queue.Receive(TimeSpan.FromSeconds(10.0));
    }
}

Remarks

When you use this overload, the callback specified in the callback parameter is invoked directly when a message becomes available in the queue or when the specified interval of time has expired; the PeekCompleted event is not raised. The other overloads of BeginPeek rely on this component to raise the PeekCompleted event.

PeekCompleted is also raised if a message already exists in the queue.

The BeginPeek method returns immediately, but the asynchronous operation is not completed until the event handler is called.

Because BeginPeek is asynchronous, you can call it to peek the queue without blocking the current thread of execution. To synchronously peek the queue, use the Peek method.

Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

BeginPeek returns a IAsyncResult that identifies the asynchronous operation that the method started. You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndPeek(IAsyncResult) is called. However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

The state object associates state information with the operation. For example, if you call BeginPeek multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.

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

BeginPeek(TimeSpan, Object)

Initiates an asynchronous peek operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginPeek(TimeSpan timeout, System::Object ^ stateObject);
public IAsyncResult BeginPeek (TimeSpan timeout, object stateObject);
member this.BeginPeek : TimeSpan * obj -> IAsyncResult
Public Function BeginPeek (timeout As TimeSpan, stateObject As Object) As IAsyncResult

Parameters

timeout
TimeSpan

A TimeSpan that indicates the interval of time to wait for a message to become available.

stateObject
Object

A state object, specified by the application, that contains information associated with the asynchronous operation.

Returns

The IAsyncResult that identifies the posted asynchronous request.

Exceptions

The value specified for the timeout parameter is not valid.

An error occurred when accessing a Message Queuing method.

Examples

The following code example creates an asynchronous peek operation, using the queue path ".\myQueue". It creates an event handler, MyPeekCompleted, and attaches it to the PeekCompleted event handler delegate. BeginPeek is called, with a time-out of one minute. Each call to BeginPeek has a unique associated integer that identifies that particular operation. When a PeekCompleted event is raised or the time-out expired, the message, if one exists, is retrieved and its body and the operation-specific integer identifier are written to the screen. Then BeginPeek is called again to initiate a new asynchronous peek operation with the same time-out and the associated integer of the just completed operation.

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;
ref class MyNewQueue
{
public:

   // Represents a state object associated with each message.
   static int messageNumber = 0;

   // Provides an event handler for the PeekCompleted
   // event.
   //
   static void MyPeekCompleted( Object^ source, PeekCompletedEventArgs^ asyncResult )
   {
      try
      {
         // Connect to the queue.
         MessageQueue^ mq = dynamic_cast<MessageQueue^>(source);

         // End the asynchronous peek operation.
         Message^ m = mq->EndPeek( asyncResult->AsyncResult );

         // Display message information on the screen, 
         // including the message number (state object).
         Console::WriteLine( "Message: {0} {1}", asyncResult->AsyncResult->AsyncState, static_cast<String^>(m->Body) );

         // Restart the asynchronous peek operation, with the 
         // same time-out.
         mq->BeginPeek( TimeSpan(0,1,0), messageNumber++ );
      }
      catch ( MessageQueueException^ e ) 
      {
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            Console::WriteLine( e );
         }

         // Handle other sources of MessageQueueException.
      }

      // Handle other exceptions.
      return;
   }
};


// Provides an entry point into the application.
//         
// This example performs asynchronous peek operation
// processing.
int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the PeekCompleted event.
   myQueue->PeekCompleted += gcnew PeekCompletedEventHandler( MyNewQueue::MyPeekCompleted );

   // Begin the asynchronous peek operation with a timeout 
   // of one minute.
   myQueue->BeginPeek( TimeSpan(0,1,0), MyNewQueue::messageNumber++ );

   // Do other work on the current thread.
   return 0;
}
using System;
using System.Messaging;

namespace MyProject
{
    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue3
    {
        // Represents a state object associated with each message.
        static int messageNumber = 0;

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example performs asynchronous peek operation
        // processing.
        //**************************************************

        public static void Main()
        {
            // Create an instance of MessageQueue. Set its formatter.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});

            // Add an event handler for the PeekCompleted event.
            myQueue.PeekCompleted += new
                PeekCompletedEventHandler(MyPeekCompleted);

            // Begin the asynchronous peek operation with a time-out
            // of one minute.
            myQueue.BeginPeek(new TimeSpan(0, 1, 0), messageNumber++);

            // Do other work on the current thread.

            return;
        }

        //**************************************************
        // Provides an event handler for the PeekCompleted
        // event.
        //**************************************************

        private static void MyPeekCompleted(Object source,
            PeekCompletedEventArgs asyncResult)
        {
            try
            {
                // Connect to the queue.
                MessageQueue mq = (MessageQueue)source;

                // End the asynchronous peek operation.
                Message m = mq.EndPeek(asyncResult.AsyncResult);

                // Display message information on the screen,
                // including the message number (state object).
                Console.WriteLine("Message: " +
                    (int)asyncResult.AsyncResult.AsyncState + " "
                    + (string)m.Body);

                // Restart the asynchronous peek operation, with the
                // same time-out.
                mq.BeginPeek(new TimeSpan(0, 1, 0), messageNumber++);
            }

            catch (MessageQueueException e)
            {
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine(e.ToString());
                }

                // Handle other sources of MessageQueueException.
            }

            // Handle other exceptions.

            return;
        }
    }
}
Imports System.Messaging


   
' Provides a container class for the example.

Public Class MyNewQueue

        ' Represents a state object associated with each message.
        Private Shared messageNumber As Integer = 0



        ' Provides an entry point into the application.
        '		 
        ' This example performs asynchronous peek operation
        ' processing.


        Public Shared Sub Main()
            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Add an event handler for the PeekCompleted event.
            AddHandler myQueue.PeekCompleted, AddressOf _
                MyPeekCompleted

            ' Begin the asynchronous peek operation with a time-out 
            ' of one minute.
            myQueue.BeginPeek(New TimeSpan(0, 1, 0), messageNumber)
            messageNumber += 1

            ' Do other work on the current thread.
            Return
        End Sub



        ' Provides an event handler for the PeekCompleted
        ' event.


        Private Shared Sub MyPeekCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As _
            PeekCompletedEventArgs)

            Try
                ' Connect to the queue.
                Dim mq As MessageQueue = _
                    CType([source], MessageQueue)

                ' End the asynchronous peek operation.
                Dim m As Message = _
                    mq.EndPeek(asyncResult.AsyncResult)

                ' Display message information on the screen, 
                ' including(the) message number (state object).
                Console.WriteLine(("Message: " + _
                    CInt(asyncResult.AsyncResult.AsyncState) + _
                    " " + CStr(m.Body)))

                ' Restart the asynchronous peek operation, with the 
                ' same time-out.
                mq.BeginPeek(New TimeSpan(0, 1, 0), messageNumber)
                messageNumber += 1


            Catch e As MessageQueueException

                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.IOTimeout Then

                    Console.WriteLine(e.ToString())

                    ' Handle other sources of MessageQueueException.

                End If

                ' Handle other exceptions.

            End Try

            Return

        End Sub

End Class

Remarks

In asynchronous processing, you use BeginPeek to raise the PeekCompleted event when a message becomes available in the queue or when the specified interval of time has expired.

PeekCompleted is also raised if a message already exists in the queue.

Use this overload to associate information with the operation that will be preserved throughout the operation's lifetime. The event handler can access this information by looking at the AsyncState property of the IAsyncResult that is associated with the operation.

To use BeginPeek, create an event handler that processes the results of the asynchronous operation, and associate it with your event delegate. BeginPeek initiates an asynchronous peek operation; the MessageQueue is notified, through the raising of the PeekCompleted event, when a message arrives in the queue. The MessageQueue can then access the message by calling EndPeek(IAsyncResult) or by retrieving the result using the PeekCompletedEventArgs.

The BeginPeek method returns immediately, but the asynchronous operation is not completed until the event handler is called.

Because BeginPeek is asynchronous, you can call it to peek the queue without blocking the current thread of execution. To synchronously peek the queue, use the Peek method.

Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

BeginPeek returns a IAsyncResult that identifies the asynchronous operation that the method started. You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndPeek(IAsyncResult) is called. However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

This overload specifies a time-out and a state object. If the interval specified by the timeout parameter expires, this component raises the PeekCompleted event. Because no message exists, a subsequent call to EndPeek(IAsyncResult) will throw an exception.

The state object associates state information with the operation. For example, if you call BeginPeek multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define. For an illustration of this scenario, see the Example section.

You can also use the state object to pass information across process threads. If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.

If CanRead is false, the completion event is raised, but an exception will be thrown when calling EndPeek(IAsyncResult).

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

BeginPeek(TimeSpan, Cursor, PeekAction, Object, AsyncCallback)

Initiates an asynchronous peek operation that has a specified time-out and that uses a specified cursor, a specified peek action, and a specified state object. The state object provides associated information throughout the lifetime of the operation. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginPeek(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Messaging::PeekAction action, System::Object ^ state, AsyncCallback ^ callback);
public IAsyncResult BeginPeek (TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.PeekAction action, object state, AsyncCallback callback);
member this.BeginPeek : TimeSpan * System.Messaging.Cursor * System.Messaging.PeekAction * obj * AsyncCallback -> IAsyncResult
Public Function BeginPeek (timeout As TimeSpan, cursor As Cursor, action As PeekAction, state As Object, callback As AsyncCallback) As IAsyncResult

Parameters

timeout
TimeSpan

A TimeSpan that indicates the interval of time to wait for a message to become available.

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.

state
Object

A state object, specified by the application, that contains information associated with the asynchronous operation.

callback
AsyncCallback

The AsyncCallback that receives the notification of the asynchronous operation completion.

Returns

The IAsyncResult that identifies the posted asynchronous request.

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.

An error occurred when accessing a Message Queuing method.

Remarks

When you use this overload, the callback specified in the callback parameter is invoked directly when a message becomes available in the queue or when the specified interval of time has expired. The PeekCompleted event is not raised. The other overloads of BeginPeek rely on this component to raise the PeekCompleted event.

PeekCompleted is also raised if a message already exists in the queue.

The BeginPeek method returns immediately, but the asynchronous operation is not completed until the event handler is called.

Because BeginPeek is asynchronous, you can call it to peek the queue without blocking the current thread of execution. To synchronously peek the queue, use the Peek method.

Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

BeginPeek returns a IAsyncResult that identifies the asynchronous operation started by the method. You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndPeek(IAsyncResult) is called. However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. In this case, use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

The state object associates state information with the operation. For example, if you call BeginPeek multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.

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

BeginPeek()

Initiates an asynchronous peek operation that has no time-out. The operation is not complete until a message becomes available in the queue.

public:
 IAsyncResult ^ BeginPeek();
public IAsyncResult BeginPeek ();
member this.BeginPeek : unit -> IAsyncResult
Public Function BeginPeek () As IAsyncResult

Returns

The IAsyncResult that identifies the posted asynchronous request.

Exceptions

An error occurred when accessing a Message Queuing method.

Examples

The following code example creates an event handler named MyPeekCompleted, attaches it to the PeekCompleted event handler delegate, and calls BeginPeek to initiate an asynchronous peek operation on the queue that is located at the path ".\myQueue". When a PeekCompleted event is raised, the example peeks the message and writes its body to the screen. The example then calls BeginPeek again to initiate a new asynchronous peek operation.

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;

// This example performs asynchronous peek operation
// processing.
//*************************************************
ref class MyNewQueue
{
public:

   // Provides an event handler for the PeekCompleted
   // event.
   static void MyPeekCompleted( Object^ source, PeekCompletedEventArgs^ asyncResult )
   {
      // Connect to the queue.
      MessageQueue^ mq = dynamic_cast<MessageQueue^>(source);

      // End the asynchronous peek operation.
      Message^ m = mq->EndPeek( asyncResult->AsyncResult );

      // Display message information on the screen.
      Console::WriteLine( "Message: {0}", static_cast<String^>(m->Body) );

      // Restart the asynchronous peek operation.
      mq->BeginPeek();
      return;
   }
};

// Provides an entry point into the application.
//         
int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the PeekCompleted event.
   myQueue->PeekCompleted += gcnew PeekCompletedEventHandler( MyNewQueue::MyPeekCompleted );

   // Begin the asynchronous peek operation.
   myQueue->BeginPeek();

   // Do other work on the current thread.
   return 0;
}
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 performs asynchronous peek operation
        // processing.
        //**************************************************

        public static void Main()
        {
            // Create an instance of MessageQueue. Set its formatter.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});

            // Add an event handler for the PeekCompleted event.
            myQueue.PeekCompleted += new
                PeekCompletedEventHandler(MyPeekCompleted);

            // Begin the asynchronous peek operation.
            myQueue.BeginPeek();

            // Do other work on the current thread.

            return;
        }

        //**************************************************
        // Provides an event handler for the PeekCompleted
        // event.
        //**************************************************

        private static void MyPeekCompleted(Object source,
            PeekCompletedEventArgs asyncResult)
        {
            // Connect to the queue.
            MessageQueue mq = (MessageQueue)source;

            // End the asynchronous peek operation.
            Message m = mq.EndPeek(asyncResult.AsyncResult);

            // Display message information on the screen.
            Console.WriteLine("Message: " + (string)m.Body);

            // Restart the asynchronous peek operation.
            mq.BeginPeek();

            return;
        }
    }
}
Imports System.Messaging





' Provides a container class for the example.
Public Class MyNewQueue



        ' Provides an entry point into the application.
        '		 
        ' This example performs asynchronous peek operation
        ' processing.


        Public Shared Sub Main()
            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Add an event handler for the PeekCompleted event.
            AddHandler myQueue.PeekCompleted, AddressOf _
                MyPeekCompleted

            ' Begin the asynchronous peek operation.
            myQueue.BeginPeek()

            ' Do other work on the current thread.
            Return
        End Sub


        '**************************************************
        ' Provides an event handler for the PeekCompleted
        ' event.
        '**************************************************

        Private Shared Sub MyPeekCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As PeekCompletedEventArgs)

            ' Connect to the queue.
            Dim mq As MessageQueue = CType([source], MessageQueue)

            ' End the asynchronous peek operation.
            Dim m As Message = mq.EndPeek(asyncResult.AsyncResult)

            ' Display message information on the screen.
            Console.WriteLine(("Message: " + CStr(m.Body)))

            ' Restart the asynchronous peek operation.
            mq.BeginPeek()

            Return

        End Sub

End Class

Remarks

In asynchronous processing, you use BeginPeek to raise the PeekCompleted event when a message becomes available in the queue.

PeekCompleted is also raised if a message already exists in the queue.

To use BeginPeek, create an event handler that processes the results of the asynchronous operation, and associate it with your event delegate. BeginPeek initiates an asynchronous peek operation; the MessageQueue is notified, through the raising of the PeekCompleted event, when a message arrives in the queue. The MessageQueue can then access the message by calling EndPeek(IAsyncResult) or by retrieving the result using the PeekCompletedEventArgs.

The BeginPeek method returns immediately, but the asynchronous operation is not completed until the event handler is called.

Because BeginPeek is asynchronous, you can call it to peek the queue without blocking the current thread of execution. To synchronously peek the queue, use the Peek method.

Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

The IAsyncResult that BeginPeek returns identifies the asynchronous operation that the method started. You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndPeek(IAsyncResult) is called. However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

If CanRead is false, the completion event is raised, but an exception will be thrown when calling EndPeek(IAsyncResult).

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

BeginPeek(TimeSpan)

Initiates an asynchronous peek operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginPeek(TimeSpan timeout);
public IAsyncResult BeginPeek (TimeSpan timeout);
member this.BeginPeek : TimeSpan -> IAsyncResult
Public Function BeginPeek (timeout As TimeSpan) As IAsyncResult

Parameters

timeout
TimeSpan

A TimeSpan that indicates the interval of time to wait for a message to become available.

Returns

The IAsyncResult that identifies the posted asynchronous request.

Exceptions

The value specified for the timeout parameter is not valid.

An error occurred when accessing a Message Queuing method.

Examples

The following code example creates an asynchronous peek operation, using the queue path ".\myQueue". It creates an event handler, MyPeekCompleted, and attaches it to the PeekCompleted event handler delegate. BeginPeek is called with a time-out of one minute, to initiate the asynchronous peek operation. When a PeekCompleted event is raised or the time-out expires, the message is retrieved if one exists, and its body is written to the screen. Then BeginPeek is called again to initiate a new asynchronous peek operation with the same time-out.

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;
ref class MyNewQueue
{
public:
   static void MyPeekCompleted( Object^ source, PeekCompletedEventArgs^ asyncResult )
   {      try
      {
         // Connect to the queue.
         MessageQueue^ mq = dynamic_cast<MessageQueue^>(source);

         // End the asynchronous peek operation.
         Message^ m = mq->EndPeek( asyncResult->AsyncResult );

         // Display message information on the screen.
         Console::WriteLine( "Message: {0}", static_cast<String^>(m->Body) );

         // Restart the asynchronous peek operation, with the 
         // same time-out.
         mq->BeginPeek( TimeSpan(0,1,0) );
      }
      catch ( MessageQueueException^ e ) 
      {
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            Console::WriteLine( e );
         }

         // Handle other sources of MessageQueueException.
      }

      // Handle other exceptions.
      return;
   }
};

int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the PeekCompleted event.
   myQueue->PeekCompleted += gcnew PeekCompletedEventHandler( MyNewQueue::MyPeekCompleted );

   // Begin the asynchronous peek operation with a timeout 
   // of one minute.
   myQueue->BeginPeek( TimeSpan(0,1,0) );

   // Do other work on the current thread.
   return 0;
}
using System;
using System.Messaging;

namespace MyProject
{
    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue2
    {
        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example performs asynchronous peek operation
        // processing.
        //**************************************************

        public static void Main()
        {
            // Create an instance of MessageQueue. Set its formatter.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});

            // Add an event handler for the PeekCompleted event.
            myQueue.PeekCompleted += new
                PeekCompletedEventHandler(MyPeekCompleted);

            // Begin the asynchronous peek operation with a time-out
            // of one minute.
            myQueue.BeginPeek(new TimeSpan(0, 1, 0));

            // Do other work on the current thread.

            return;
        }

        //**************************************************
        // Provides an event handler for the PeekCompleted
        // event.
        //**************************************************

        private static void MyPeekCompleted(Object source,
            PeekCompletedEventArgs asyncResult)
        {
            try
            {
                // Connect to the queue.
                MessageQueue mq = (MessageQueue)source;

                // End the asynchronous peek operation.
                Message m = mq.EndPeek(asyncResult.AsyncResult);

                // Display message information on the screen.
                Console.WriteLine("Message: " + (string)m.Body);

                // Restart the asynchronous peek operation, with the
                // same time-out.
                mq.BeginPeek(new TimeSpan(0, 1, 0));
            }

            catch (MessageQueueException e)
            {
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine(e.ToString());
                }

                // Handle other sources of MessageQueueException.
            }

            // Handle other exceptions.

            return;
        }
    }
}
Imports System.Messaging


' Provides a container class for the example.
Public Class MyNewQueue



        ' Provides an entry point into the application.
        '		 
        ' This example performs asynchronous peek operation
        ' processing.


        Public Shared Sub Main()
            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                    {GetType([String])})

            ' Add an event handler for the PeekCompleted event.
            AddHandler myQueue.PeekCompleted, _
                    AddressOf MyPeekCompleted

            ' Begin the asynchronous peek operation with a time-out 
            ' of one minute.
            myQueue.BeginPeek(New TimeSpan(0, 1, 0))

            ' Do other work on the current thread.
            Return

        End Sub



        ' Provides an event handler for the PeekCompleted
        ' event.


        Private Shared Sub MyPeekCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As _
            PeekCompletedEventArgs)

            Try
                ' Connect to the queue.
                Dim mq As MessageQueue = CType([source], _
                    MessageQueue)

                ' End the asynchronous peek operation.
                Dim m As Message = _
                    mq.EndPeek(asyncResult.AsyncResult)

                ' Display message information on the screen.
                Console.WriteLine(("Message: " + CStr(m.Body)))

                ' Restart the asynchronous peek operation, with the 
                ' same time-out.
                mq.BeginPeek(New TimeSpan(0, 1, 0))

            Catch e As MessageQueueException

                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.IOTimeout Then

                    Console.WriteLine(e.ToString())

                    ' Handle other sources of MessageQueueException.
                End If

                ' Handle other exceptions.

            End Try

            Return

        End Sub

End Class

Remarks

In asynchronous processing, you use BeginPeek to raise the PeekCompleted event when a message becomes available in the queue or when the specified interval of time has expired.

PeekCompleted is also raised if a message already exists in the queue.

To use BeginPeek, create an event handler that processes the results of the asynchronous operation, and associate it with your event delegate. BeginPeek initiates an asynchronous peek operation; the MessageQueue is notified, through the raising of the PeekCompleted event, when a message arrives in the queue. The MessageQueue can then access the message by calling EndPeek(IAsyncResult) or by retrieving the result using the PeekCompletedEventArgs.

The BeginPeek method returns immediately, but the asynchronous operation is not completed until the event handler is called.

Because BeginPeek is asynchronous, you can call it to peek the queue without blocking the current thread of execution. To synchronously peek the queue, use the Peek method.

Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

The IAsyncResult that BeginPeek returns identifies the asynchronous operation that the method started. You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndPeek(IAsyncResult) is called. However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

This overload specifies a time-out. If the interval specified by the timeout parameter expires, this component raises the PeekCompleted event. Because no message exists, a subsequent call to EndPeek(IAsyncResult) will throw an exception.

If CanRead is false, the completion event is raised, but an exception will be thrown when calling EndPeek(IAsyncResult).

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

Thread Safety

The method is not thread safe.