MessageQueue.Peek 方法

定義

回傳佇列中第一個訊息的副本,但不會將該訊息從佇列中移除。

多載

名稱 Description
Peek()

回傳時不移除(窺見)佇列 MessageQueue中由 參考的第一個訊息。 此 Peek() 方法為同步式,因此會阻擋目前執行緒,直到訊息可用。

Peek(TimeSpan)

回傳時不移除(窺見)佇列 MessageQueue中由 參考的第一個訊息。 此 Peek() 方法是同步的,因此會阻擋目前執行緒,直到訊息可用或指定的逾時發生。

Peek(TimeSpan, Cursor, PeekAction)

使用指定的游標返回,但不會移除(窺見)佇列中的目前或下一則訊息。 此 Peek() 方法是同步的,因此會阻擋目前執行緒,直到訊息可用或指定的逾時發生。

Peek()

回傳時不移除(窺見)佇列 MessageQueue中由 參考的第一個訊息。 此 Peek() 方法為同步式,因此會阻擋目前執行緒,直到訊息可用。

public:
 System::Messaging::Message ^ Peek();
public System.Messaging.Message Peek();
member this.Peek : unit -> System.Messaging.Message
Public Function Peek () As Message

傳回

the Message that 代表隊列中的第一個訊息。

例外狀況

存取訊息佇列方法時發生錯誤。

範例

以下範例在隊列上使用該 Peek 方法。

在第一個例子中,應用程式會等待佇列中有訊息可用。 請注意,第一個範例並未存取抵達的訊息;它只是暫停處理,直到訊息抵達。 如果訊息已經存在於佇列中,該訊息會立即返回。

在第二個例子中,包含應用程式定義 Order 類別的訊息會被送入佇列,然後從佇列中偷看。

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

using namespace System;
using namespace System::Messaging;

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


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

   //*************************************************
   // Posts a notification when a message arrives in 
   // the queue S"monitoredQueue". Does not retrieve any 
   // message information when peeking the message.
   //*************************************************
   void NotifyArrived()
   {
      // Connect to a queue.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\monitoredQueue" );

      // Specify to retrieve no message information.
      myQueue->MessageReadPropertyFilter->ClearAll();

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

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


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

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

      // Send the Order to the queue.
      myQueue->Send( sentOrder );
      return;
   }

   //*************************************************
   // Peeks a message containing an Order.
   //*************************************************
   void PeekFirstMessage()
   {
      // Connect to a queue.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Set the formatter to indicate the body contains an Order.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = Order::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );
      try
      {
         // Peek and format the message. 
         Message^ myMessage = myQueue->Peek();
         Order^ myOrder = static_cast<Order^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( "Order ID: {0}", myOrder->orderId );
         Console::WriteLine( "Sent: {0}", myOrder->orderTime );
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle Message Queuing exceptions.
      }
      // Handle invalid serialization format.
      catch ( InvalidOperationException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

      // Catch other exceptions as necessary.
      return;
   }
};

//*************************************************
// Provides an entry point into the application.
//         
// This example posts a notification that a message
// has arrived in a queue. It sends a message 
// containing an other to a separate queue, and then
// peeks the first message in the queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

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

   // Peek the first message in the queue.
   myNewQueue->PeekFirstMessage();
   return 0;
}
using System;
using System.Messaging;

namespace MyProject
{

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

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

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

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

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

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

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

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

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

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

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

            return;
        }

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

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

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

            return;
        }

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

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

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

            return;
        }
    }
}
Imports System.Messaging



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


   
    Public Class MyNewQueue


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

        Public Shared Sub Main()

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

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

            ' Send a message to a queue.
            myNewQueue.SendMessage()

            ' Peek the first message in the queue.
            myNewQueue.PeekFirstMessage()

            Return

        End Sub


        
        ' Posts a notification when a message arrives in 
        ' the queue "monitoredQueue". Does not retrieve any 
        ' message information when peeking the message.
        
        Public Sub NotifyArrived()

            ' Connect to a queue.
            Dim myQueue As New MessageQueue(".\monitoredQueue")

            ' Specify to retrieve no message information.
            myQueue.MessageReadPropertyFilter.ClearAll()

            ' Wait for a message to arrive. 
            Dim emptyMessage As Message = myQueue.Peek()

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

            Return

        End Sub


        
        ' Sends an Order to a queue.
        

        Public Sub SendMessage()

            ' Create a new order and set values.
            Dim sentOrder As New Order()
            sentOrder.orderId = 3
            sentOrder.orderTime = DateTime.Now

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

            ' Send the Order to the queue.
            myQueue.Send(sentOrder)

            Return

        End Sub


        
        ' Peeks a message containing an Order.
        

        Public Sub PeekFirstMessage()

            ' Connect to a queue.
            Dim myQueue As New MessageQueue(".\myQueue")

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

            Try

                ' Peek and format the message. 
                Dim myMessage As Message = myQueue.Peek()
                Dim myOrder As Order = CType(myMessage.Body, Order)

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

            Catch m as MessageQueueException
                ' Handle Message Queuing exceptions.


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

                ' Catch other exceptions as necessary.

            End Try

            Return

        End Sub

End Class

備註

利用此超載來窺探佇列,或等待佇列中出現訊息。

Peek 方法會讀取,但不會移除佇列中的第一個訊息。 因此,除非有更高優先權的訊息抵達佇列,否則會反覆呼叫以回 Peek 傳相同的訊息。 而此 Receive 方法則同時讀取並移除第一則訊息。 重複呼叫 Receive,因此會返回不同的訊息。

訊息排隊會依優先順序和抵達時間排序排隊中的訊息。 只有當新訊息優先權較高時,才會將其置於舊訊息之前。

當目前執行緒在等待訊息到達隊列時被封鎖,才會使用 Peek 。 由於此超載未指定逾時,應用程式可能會無限期等待。 如果你需要申請流程繼續而不等,請使用非同步 BeginPeek 方法。 或者,你也可以利用指定逾時的超載來指定訊息到達佇列的逾時 Peek

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

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

Peek(TimeSpan)

回傳時不移除(窺見)佇列 MessageQueue中由 參考的第一個訊息。 此 Peek() 方法是同步的,因此會阻擋目前執行緒,直到訊息可用或指定的逾時發生。

public:
 System::Messaging::Message ^ Peek(TimeSpan timeout);
public System.Messaging.Message Peek(TimeSpan timeout);
member this.Peek : TimeSpan -> System.Messaging.Message
Public Function Peek (timeout As TimeSpan) As Message

參數

timeout
TimeSpan

A TimeSpan 表示等待隊列中包含訊息的最大時間。

傳回

the Message that 代表隊列中的第一個訊息。

例外狀況

參數指定的 timeout 值不成立,可能 timeoutZero 於或大於 InfiniteTimeout

存取訊息佇列方法時發生錯誤。

範例

以下程式碼範例使用 Peek 逾時為零的方法來檢查佇列是否為空。

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

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

   //*************************************************
   // Determines whether a queue is empty. The Peek()
   // method throws an exception if there is no message
   // in the queue. This method handles that exception 
   // by returning true to the calling method.
   //*************************************************
   bool IsQueueEmpty()
   {
      bool isQueueEmpty = false;
      
      // Connect to a queue.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
      try
      {
         
         // Set Peek to return immediately.
         myQueue->Peek( TimeSpan(0) );
         
         // If an IOTime->Item[Out] was* not thrown, there is a message 
         // in the queue.
         isQueueEmpty = false;
      }
      catch ( MessageQueueException^ e ) 
      {
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            
            // No message was in the queue.
            isQueueEmpty = true;
         }

         
         // Handle other sources of MessageQueueException.
      }

      
      // Handle other exceptions as necessary.
      // Return true if there are no messages in the queue.
      return isQueueEmpty;
   }

};


//*************************************************
// Provides an entry point into the application.
//         
// This example determines whether a queue is empty.
//*************************************************
int main()
{
   
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;
   
   // Determine whether a queue is empty.
   bool isQueueEmpty = myNewQueue->IsQueueEmpty();
   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 determines whether a queue is empty.
        //**************************************************

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

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

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

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

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

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

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

                // Handle other sources of MessageQueueException.
            }

            // Handle other exceptions as necessary.

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



   
    Public Class MyNewQueue


        '
        ' Provides an entry point into the application.
        '		 
        ' This example determines whether a queue is empty.
        '

        Public Shared Sub Main()

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

            ' Determine whether a queue is empty.
            Dim IsQueueEmpty As Boolean = myNewQueue.IsQueueEmpty()
        if IsQueueEMpty=True Then Console.WriteLine("Empty")
            

            Return

        End Sub


        '
        ' Determines whether a queue is empty. The Peek()
        ' method throws an exception if there is no message
        ' in the queue. This method handles that exception 
        ' by returning true to the calling method.
        '

        Public Function IsQueueEmpty() As Boolean

            'Dim QueueEmpty As Boolean = False

            ' Connect to a queue.
            Dim myQueue As New MessageQueue(".\myQueue")

            Try

                ' Set Peek to return immediately.
                myQueue.Peek(New TimeSpan(0))

                ' If an IOTimeout was not thrown, there is a message 
                ' in the queue.
                'queueEmpty = False

            Catch e As MessageQueueException

                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.IOTimeout Then

                    ' No message was in the queue.
                    IsQueueEmpty = True

                End If

                ' Handle other sources of MessageQueueException as necessary.

                ' Handle other exceptions as necessary.

            End Try

            ' Return true if there are no messages in the queue.
            'Return queueEmpty
        IsQueueEmpty = False

        End Function 'IsQueueEmpty 

End Class

備註

利用此超載方式窺探佇列,或等待指定時間直到隊列中出現訊息。 如果佇列中已有訊息,該方法會立即回傳。

Peek 方法會讀取,但不會移除佇列中的第一個訊息。 因此,除非有更高優先權的訊息抵達佇列,否則會反覆呼叫以回 Peek 傳相同的訊息。 而此 Receive 方法則同時讀取並移除第一則訊息。 重複呼叫 Receive,因此會返回不同的訊息。

訊息排隊會依優先順序和抵達時間排序排隊中的訊息。 只有當新訊息優先權較高時,才會將其置於舊訊息之前。

當目前執行緒在等待訊息到達隊列時被封鎖,才會使用 Peek 。 該討論串會在指定時間內被封鎖,若你指定 InfiniteTimeout,則無限期封鎖。 如果你需要申請流程繼續而不等,請使用非同步 BeginPeek 方法。

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

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

Peek(TimeSpan, Cursor, PeekAction)

使用指定的游標返回,但不會移除(窺見)佇列中的目前或下一則訊息。 此 Peek() 方法是同步的,因此會阻擋目前執行緒,直到訊息可用或指定的逾時發生。

public:
 System::Messaging::Message ^ Peek(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Messaging::PeekAction action);
public System.Messaging.Message Peek(TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.PeekAction action);
member this.Peek : TimeSpan * System.Messaging.Cursor * System.Messaging.PeekAction -> System.Messaging.Message
Public Function Peek (timeout As TimeSpan, cursor As Cursor, action As PeekAction) As Message

參數

timeout
TimeSpan

A TimeSpan 表示等待隊列中包含訊息的最大時間。

cursor
Cursor

A Cursor 在訊息佇列中維持特定位置。

action
PeekAction

這是其中一項 PeekAction 價值。 指示是查看隊列中的當前訊息,還是下一則訊息。

傳回

Message代表佇列中的訊息。

例外狀況

參數指定PeekAction.Current了除 PeekAction.Next or action 以外的值。

參數 cursornull

timeout 參數指定的值無效。 可能 timeoutZero 於或大於 InfiniteTimeout

存取訊息佇列方法時發生錯誤。

備註

利用此超載方式窺探佇列,或等待指定時間直到隊列中出現訊息。 如果佇列中已有訊息,該方法會立即回傳。

Peek 方法會讀取但不會移除佇列中的訊息。 而此 Receive 方法則同時讀取並移除佇列中的訊息。

當目前執行緒在等待訊息到達隊列時被封鎖,才會使用 Peek 。 該執行緒會在指定時間內被封鎖,或如果你指定 InfiniteTimeout為 則無限期封鎖。 如果你需要申請流程繼續而不等,請使用非同步 BeginPeek 方法。

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

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

執行緒安全性

這個方法並不安全於執行緒。