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

備註

當您使用此多載時,會在佇列中使用訊息或指定的時間間隔過期時,直接叫用回呼參數中指定的回呼; PeekCompleted 未引發事件。 的其他多載 BeginPeek 會依賴此元件來引發 PeekCompleted 事件。

PeekCompleted 如果佇列中已有訊息,也會引發 。

方法 BeginPeek 會立即傳回,但在呼叫事件處理程式之前,不會完成異步操作。

因為 BeginPeek 是異步的,所以您可以呼叫它來查看佇列,而不封鎖目前的線程執行。 若要同步查看佇列,請使用 Peek 方法。

異步操作完成後,您可以在事件處理程式中呼叫 或 BeginReceive 再次呼叫 BeginPeek ,以保留接收通知。

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 稱為 ,逾時為一分鐘。 每個的呼叫 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 方法。

異步操作完成後,您可以在事件處理程式中呼叫 或 BeginReceive 再次呼叫 BeginPeek ,以保留接收通知。

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 方法。

異步操作完成後,您可以在事件處理程式中呼叫 或 BeginReceive 再次呼叫 BeginPeek ,以保留接收通知。

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 方法。

異步操作完成後,您可以在事件處理程式中呼叫 或 BeginReceive 再次呼叫 BeginPeek ,以保留接收通知。

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 方法。

異步操作完成後,您可以在事件處理程式中呼叫 或 BeginReceive 再次呼叫 BeginPeek ,以保留接收通知。

IAsyncResultBeginPeek會識別方法啟動的異步操作。 您可以在作業的整個存留期內使用此 IAsyncResult 項目,雖然您通常不會在呼叫之前 EndPeek(IAsyncResult) 使用它。 不過,如果您啟動數個異步操作,您可以將其 IAsyncResult 值放在陣列中,並指定是否要等候所有作業或任何作業完成。 在此情況下,您會使用 AsyncWaitHandleIAsyncResult 屬性來識別已完成的作業。

此多載會指定逾時。如果參數指定的 timeout 間隔過期,此元件會 PeekCompleted 引發 事件。 由於沒有任何訊息存在,後續呼叫 EndPeek(IAsyncResult) 將會擲回例外狀況。

如果 為 CanReadfalse,則會引發完成事件,但在呼叫 EndPeek(IAsyncResult)時會擲回例外狀況。

下表顯示此方法是否可在各種工作組模式中使用。

工作組模式 可用
本機電腦
本機計算機和直接格式名稱
遠端電腦
遠端電腦和直接格式名稱

另請參閱

適用於

執行緒安全性

方法不是安全線程。