MessageQueue.BeginPeek 方法

定义

通过通知“消息队列”开始查看消息并在完成后通知事件处理程序,启动一个异步查看操作。

重载

BeginPeek(TimeSpan, Object, AsyncCallback)

启动具有指定超时设定和指定状态对象的异步查看操作,此状态对象在操作的整个生存期内提供相关信息。 此重载通过回调接收操作的事件处理程序标识的通知。 直到队列中出现消息时或发生超时时才完成操作。

BeginPeek(TimeSpan, Object)

启动具有指定超时设定和指定状态对象的异步查看操作,此状态对象在操作的整个生存期内提供相关信息。 直到队列中出现消息时或发生超时时才完成操作。

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

启动异步查看操作,此操作具有指定的超时并使用指定的游标、指定的查看操作和指定的状态对象。 状态对象在操作的整个生存期内提供相关的信息。 此重载通过回调接收操作的事件处理程序标识的通知。 直到队列中出现消息时或发生超时时才完成操作。

BeginPeek()

启动一个未设置超时的异步查看操作。直到队列中有可用消息时,操作才会完成。

BeginPeek(TimeSpan)

启动具有指定超时的异步查看操作。直到队列中有可用消息或发生超时,操作才会完成。

BeginPeek(TimeSpan, Object, AsyncCallback)

启动具有指定超时设定和指定状态对象的异步查看操作,此状态对象在操作的整个生存期内提供相关信息。 此重载通过回调接收操作的事件处理程序标识的通知。 直到队列中出现消息时或发生超时时才完成操作。

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

参数

timeout
TimeSpan

一个 TimeSpan 指示等待消息变为可用所用的时间间隔。

stateObject
Object

应用程序指定的状态对象,包含与异步操作关联的信息。

callback
AsyncCallback

AsyncCallback 将接收异步操作完成通知。

返回

IAsyncResult 标识已发布的异步请求的。

例外

timeout 参数指定的值无效。

访问“消息队列”方法时出错。

示例

下面的代码示例创建异步速览操作。 该代码示例将消息发送到本地消息队列,然后调用 BeginPeek(TimeSpan, Object, AsyncCallback),传入 :超时值 10 秒;标识该特定消息的唯一整数;以及标识事件处理程序MyPeekCompleted的新实例 AsyncCallbackPeekCompleted引发事件时,事件处理程序将扫视消息,并将消息正文和整数消息标识符写入屏幕。

#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));
    }
}

注解

使用此重载时,当消息在队列中可用或指定的时间间隔已过期时,将直接调用 callback 参数中指定的回调; PeekCompleted 未引发 事件。 的其他重载 BeginPeek 依赖于此组件来引发 PeekCompleted 事件。

PeekCompleted 如果队列中已存在消息,也会引发 。

方法 BeginPeek 会立即返回,但异步操作在调用事件处理程序之前不会完成。

由于 BeginPeek 是异步的,因此可以调用它来查看队列,而不会阻止当前执行线程。 若要同步查看队列,请使用 Peek 方法。

异步操作完成后,可以在事件处理程序中再次调用 BeginPeekBeginReceive 以继续接收通知。

BeginPeek 返回一个 , IAsyncResult 它标识方法启动的异步操作。 可以在操作的整个生存期内使用它 IAsyncResult ,尽管在调用 之前 EndPeek(IAsyncResult) 通常不会使用它。 但是,如果启动多个异步操作,则可以将其 IAsyncResult 值放在数组中,并指定是等待所有操作还是等待任何操作完成。 在这种情况下,使用 AsyncWaitHandleIAsyncResult 属性来标识已完成的操作。

状态对象将状态信息与操作相关联。 例如,如果多次调用 BeginPeek 以启动多个操作,则可以通过定义的单独状态对象来标识每个操作。

下表显示了此方法在各种工作组模式下是否可用。

工作组模式 可用
本地计算机
本地计算机和直接格式名称
远程计算机
远程计算机和直接格式名称

另请参阅

适用于

BeginPeek(TimeSpan, Object)

启动具有指定超时设定和指定状态对象的异步查看操作,此状态对象在操作的整个生存期内提供相关信息。 直到队列中出现消息时或发生超时时才完成操作。

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

参数

timeout
TimeSpan

一个 TimeSpan 指示等待消息变为可用所用的时间间隔。

stateObject
Object

应用程序指定的状态对象,包含与异步操作关联的信息。

返回

IAsyncResult 标识已发布的异步请求的。

例外

timeout 参数指定的值无效。

访问“消息队列”方法时出错。

示例

下面的代码示例使用队列路径“.\myQueue”创建异步速览操作。 它创建事件处理程序 MyPeekCompleted,并将其附加到 PeekCompleted 事件处理程序委托。 BeginPeek 调用 ,超时为 1 分钟。 对 BeginPeek 的每个调用都有一个唯一的关联整数,用于标识该特定操作。 PeekCompleted当引发事件或超时过期时,将检索消息(如果存在)并将其正文和特定于操作的整数标识符写入屏幕。 然后 BeginPeek 再次调用 以启动具有相同超时和刚刚完成操作的关联整数的新异步速览操作。

#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

注解

在异步处理中,当消息在队列中可用或指定的时间间隔已过期时,使用 BeginPeek 引发 PeekCompleted 事件。

PeekCompleted 如果队列中已存在消息,也会引发 。

使用此重载将信息与将在操作的整个生存期内保留的操作相关联。 事件处理程序可以通过查看 AsyncState 与操作关联的 的 IAsyncResult 属性来访问此信息。

若要使用 BeginPeek,请创建一个事件处理程序来处理异步操作的结果,并将其与事件委托相关联。 BeginPeek 启动异步速览操作; MessageQueue 当消息到达队列时,将通过引发 PeekCompleted 事件来通知 。 然后, MessageQueue 可以通过调用 EndPeek(IAsyncResult) 或使用 检索结果 PeekCompletedEventArgs来访问消息。

方法 BeginPeek 会立即返回,但异步操作在调用事件处理程序之前不会完成。

由于 BeginPeek 是异步的,因此可以调用它来查看队列,而不会阻止当前执行线程。 若要同步查看队列,请使用 Peek 方法。

异步操作完成后,可以在事件处理程序中再次调用 BeginPeekBeginReceive 以继续接收通知。

BeginPeek 返回一个 , IAsyncResult 它标识方法启动的异步操作。 可以在操作的整个生存期内使用它 IAsyncResult ,尽管在调用 之前 EndPeek(IAsyncResult) 通常不会使用它。 但是,如果启动多个异步操作,则可以将其 IAsyncResult 值放在数组中,并指定是等待所有操作还是等待任何操作完成。 在这种情况下,使用 AsyncWaitHandleIAsyncResult 属性来标识已完成的操作。

此重载指定超时和状态对象。 如果 参数指定的 timeout 时间间隔过期,此组件将 PeekCompleted 引发 事件。 由于不存在任何消息,因此对 的 EndPeek(IAsyncResult) 后续调用将引发异常。

状态对象将状态信息与操作相关联。 例如,如果多次调用 BeginPeek 以启动多个操作,则可以通过定义的单独状态对象来标识每个操作。 有关此方案的插图,请参阅示例部分。

还可以使用状态对象跨进程线程传递信息。 如果线程已启动,但回调位于异步方案中的不同线程上,则状态对象将被封送并连同事件中的信息一起传回。

如果 CanReadfalse,则会引发完成事件,但在调用 EndPeek(IAsyncResult)时将引发异常。

下表显示了此方法在各种工作组模式下是否可用。

工作组模式 可用
本地计算机
本地计算机和直接格式名称
远程计算机
远程计算机和直接格式名称

另请参阅

适用于

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

启动异步查看操作,此操作具有指定的超时并使用指定的游标、指定的查看操作和指定的状态对象。 状态对象在操作的整个生存期内提供相关的信息。 此重载通过回调接收操作的事件处理程序标识的通知。 直到队列中出现消息时或发生超时时才完成操作。

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

参数

timeout
TimeSpan

一个 TimeSpan 指示等待消息变为可用所用的时间间隔。

cursor
Cursor

维持消息队列中特定位置的 Cursor

action
PeekAction

PeekAction 值之一。 指示是查看队列中的当前消息还是下一条消息。

state
Object

应用程序指定的状态对象,包含与异步操作关联的信息。

callback
AsyncCallback

AsyncCallback 将接收异步操作完成通知。

返回

IAsyncResult 标识已发布的异步请求的。

例外

action 参数指定的值不是 PeekAction.CurrentPeekAction.Next

cursor 参数为 null

timeout 参数指定的值无效。

访问“消息队列”方法时出错。

注解

使用此重载时,当消息在队列中可用或指定的时间间隔过期时,将直接调用回调参数中指定的回调。 PeekCompleted不会引发 事件。 的其他重载 BeginPeek 依赖于此组件来引发 PeekCompleted 事件。

PeekCompleted 如果队列中已存在消息,也会引发 。

方法 BeginPeek 会立即返回,但在调用事件处理程序之前,异步操作不会完成。

由于 BeginPeek 是异步的,因此可以调用它来查看队列,而不会阻止当前执行线程。 若要同步查看队列,请使用 Peek 方法。

异步操作完成后,可以在事件处理程序中再次调用 BeginPeekBeginReceive 以继续接收通知。

BeginPeek 返回一个 IAsyncResult ,它标识由 方法启动的异步操作。 可以在操作的整个生存期内使用它 IAsyncResult ,尽管在调用 之前 EndPeek(IAsyncResult) 通常不会使用它。 但是,如果启动多个异步操作,则可以将其 IAsyncResult 值放在数组中,并指定是等待所有操作完成还是等待任何操作完成。 在这种情况下,请使用 AsyncWaitHandleIAsyncResult 属性来标识已完成的操作。

状态对象将状态信息与操作相关联。 例如,如果多次调用 BeginPeek 以启动多个操作,则可以通过定义的单独状态对象来标识每个操作。

下表显示了此方法是否在各种工作组模式下可用。

工作组模式 可用
本地计算机
本地计算机和直接格式名称
远程计算机
远程计算机和直接格式名称

另请参阅

适用于

BeginPeek()

启动一个未设置超时的异步查看操作。直到队列中有可用消息时,操作才会完成。

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

返回

IAsyncResult 标识已发布的异步请求的。

例外

访问“消息队列”方法时出错。

示例

下面的代码示例创建一个名为 MyPeekCompleted的事件处理程序,将其 PeekCompleted 附加到事件处理程序委托,并调用 BeginPeek 以对位于路径“.\myQueue”的队列启动异步速览操作。 PeekCompleted引发事件时,该示例将速览消息并将其正文写入屏幕。 然后,该示例再次调用 BeginPeek 以启动新的异步速览操作。

#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

注解

在异步处理中,使用 BeginPeek 在队列中提供消息时引发 PeekCompleted 事件。

PeekCompleted 如果队列中已存在消息,也会引发 。

若要使用 BeginPeek,请创建一个事件处理程序来处理异步操作的结果,并将其与事件委托相关联。 BeginPeek 启动异步速览操作; MessageQueue 当消息到达队列时,通过引发 PeekCompleted 事件通知 。 然后, MessageQueue 可以通过调用 EndPeek(IAsyncResult) 或使用 检索结果 PeekCompletedEventArgs来访问消息。

方法 BeginPeek 会立即返回,但在调用事件处理程序之前,异步操作不会完成。

由于 BeginPeek 是异步的,因此可以调用它来查看队列,而不会阻止当前执行线程。 若要同步查看队列,请使用 Peek 方法。

异步操作完成后,可以在事件处理程序中再次调用 BeginPeekBeginReceive 以继续接收通知。

IAsyncResultBeginPeek返回的 标识方法启动的异步操作。 可以在操作的整个生存期内使用它 IAsyncResult ,尽管在调用 之前 EndPeek(IAsyncResult) 通常不会使用它。 但是,如果启动多个异步操作,则可以将其 IAsyncResult 值放在数组中,并指定是等待所有操作完成还是等待任何操作完成。 在这种情况下,使用 AsyncWaitHandleIAsyncResult 属性来标识已完成的操作。

如果 CanReadfalse,则会引发完成事件,但在调用 EndPeek(IAsyncResult)时将引发异常。

下表显示了此方法是否在各种工作组模式下可用。

工作组模式 可用
本地计算机
本地计算机和直接格式名称
远程计算机
远程计算机和直接格式名称

另请参阅

适用于

BeginPeek(TimeSpan)

启动具有指定超时的异步查看操作。直到队列中有可用消息或发生超时,操作才会完成。

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

参数

timeout
TimeSpan

一个 TimeSpan 指示等待消息变为可用所用的时间间隔。

返回

IAsyncResult 标识已发布的异步请求的。

例外

timeout 参数指定的值无效。

访问“消息队列”方法时出错。

示例

下面的代码示例使用队列路径“.\myQueue”创建异步速览操作。 它创建事件处理程序 , MyPeekCompleted并将其附加到 PeekCompleted 事件处理程序委托。 BeginPeek 调用 时超时为一分钟,以启动异步速览操作。 PeekCompleted当引发事件或超时过期时,将检索消息(如果存在),并且其正文将写入屏幕。 然后 BeginPeek 再次调用 以启动具有相同超时的新异步速览操作。

#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

注解

在异步处理中,使用 BeginPeek 在队列中提供消息或指定的时间间隔过期时引发 PeekCompleted 事件。

PeekCompleted 如果队列中已存在消息,也会引发 。

若要使用 BeginPeek,请创建一个事件处理程序来处理异步操作的结果,并将其与事件委托相关联。 BeginPeek 启动异步速览操作; MessageQueue 当消息到达队列时,通过引发 PeekCompleted 事件通知 。 然后, MessageQueue 可以通过调用 EndPeek(IAsyncResult) 或使用 检索结果 PeekCompletedEventArgs来访问消息。

方法 BeginPeek 会立即返回,但在调用事件处理程序之前,异步操作不会完成。

由于 BeginPeek 是异步的,因此可以调用它来查看队列,而不会阻止当前执行线程。 若要同步查看队列,请使用 Peek 方法。

异步操作完成后,可以在事件处理程序中再次调用 BeginPeekBeginReceive 以继续接收通知。

IAsyncResultBeginPeek返回的 标识方法启动的异步操作。 可以在操作的整个生存期内使用它 IAsyncResult ,尽管在调用 之前 EndPeek(IAsyncResult) 通常不会使用它。 但是,如果启动多个异步操作,则可以将其 IAsyncResult 值放在数组中,并指定是等待所有操作完成还是等待任何操作完成。 在这种情况下,使用 AsyncWaitHandleIAsyncResult 属性来标识已完成的操作。

此重载指定超时。如果 参数指定的 timeout 间隔过期,则此组件将 PeekCompleted 引发 事件。 由于不存在任何消息,因此对 EndPeek(IAsyncResult) 的后续调用将引发异常。

如果 CanReadfalse,则会引发完成事件,但在调用 EndPeek(IAsyncResult)时将引发异常。

下表显示了此方法是否在各种工作组模式下可用。

工作组模式 可用
本地计算机
本地计算机和直接格式名称
远程计算机
远程计算机和直接格式名称

另请参阅

适用于

线程安全性

方法不是线程安全的。