MessageQueue.Peek 方法

定义

返回队列中第一条消息的副本,而不从队列中移除该消息。

重载

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

返回

Message 表示队列中第一条消息。

例外

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

示例

以下示例在队列上使用 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 指定超时,为到达队列的消息指定超时。

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

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

另请参阅

适用于

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

一个 TimeSpan 指示等待队列包含消息所用的最长时间。

返回

Message 表示队列中第一条消息。

例外

timeout 参数指定的值无效,可能是 timeout 小于 Zero 或大于 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 方法。

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

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

另请参阅

适用于

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

一个 TimeSpan 指示等待队列包含消息所用的最长时间。

cursor
Cursor

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

action
PeekAction

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

返回

一个 Message,表示队列中的消息。

例外

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

cursor 参数为 null

timeout 参数指定的值无效。 timeout 可能小于 Zero 或大于 InfiniteTimeout

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

注解

使用此重载可查看队列,或等待指定时间段,直到队列中存在消息。 如果队列中已存在消息,该方法将立即返回 。

方法 Peek 从队列中读取消息,但不删除消息。 Receive另一方面, 方法读取和删除队列中的消息。

如果当前线程在等待消息到达队列时可以被阻塞,则使用 Peek。 线程被阻塞到指定的时间段,或者,如果指示 ,则无限期地阻止该线程 InfiniteTimeout。 如果需要应用程序处理继续进行而不等待,则使用异步 BeginPeek 方法。

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

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

另请参阅

适用于

线程安全性

方法不是线程安全的。