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 오버로드를 사용하여 메시지가 큐에 도착할 시간 초과를 지정할 수 있습니다.

다음 표에서는 이 메서드를 다양한 작업 그룹 모드에서 사용할 수 있는지 여부를 보여 줍니다.

작업 그룹 모드 사용 가능
수집 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

큐가 메시지를 포함하도록 대기하는 최대 시간을 나타내는 TimeSpan입니다.

반환

큐에 있는 첫 번째 메시지를 나타내는 Message를 반환합니다.

예외

timeout 매개 변수에 지정된 값이 잘못된 경우. timeoutZero보다 작거나 InfiniteTimeout보다 클 수 있습니다.

메시지 큐 메서드에 액세스하는 동안 오류가 발생한 경우

예제

다음 코드 예제에서는 시간 초과가 Peek 0인 메서드를 사용하여 큐가 비어 있는지 여부를 검사.

#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 메서드를 사용합니다.

다음 표에서는 이 메서드를 다양한 작업 그룹 모드에서 사용할 수 있는지 여부를 보여 줍니다.

작업 그룹 모드 사용 가능
수집 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

큐가 메시지를 포함하도록 대기하는 최대 시간을 나타내는 TimeSpan입니다.

cursor
Cursor

메시지 큐에서 특정 위치를 유지하는 Cursor입니다.

action
PeekAction

PeekAction 값 중 하나입니다. 이 값은 큐의 현재 메시지를 피킹할지 또는 다음 메시지를 피킹할지 여부를 나타냅니다.

반환

큐에 있는 메시지를 나타내는 Message입니다.

예외

action 매개 변수에 대해 PeekAction.Current 또는 PeekAction.Next 이외의 값을 지정했습니다.

cursor 매개 변수가 null인 경우

timeout 매개 변수에 지정된 값이 잘못된 경우 timeoutZero보다 작거나 InfiniteTimeout보다 클 수 있습니다.

메시지 큐 메서드에 액세스하는 동안 오류가 발생한 경우

설명

이 오버로드를 사용하여 큐를 피킹하거나 큐에 메시지가 있을 때까지 지정된 기간을 기다립니다. 메시지가 큐에 이미 있으면 메서드가 즉시 반환됩니다.

메서드는 Peek 큐에서 메시지를 읽지만 제거하지는 않습니다. 반면에 메서드는 Receive 큐에서 메시지를 읽고 제거합니다.

큐에 메시지가 도착할 때까지 대기하는 동안 현재 스레드를 차단하는 것이 허용되는 경우에만 Peek를 사용합니다. 스레드는 지정된 기간까지 차단되거나 를 표시한 경우 무기한으로 차단됩니다 InfiniteTimeout. 대기하지 않고 애플리케이션 처리를 계속하려면 비동기 BeginPeek 메서드를 사용합니다.

다음 표에서는 이 메서드를 다양한 작업 그룹 모드에서 사용할 수 있는지 여부를 보여 줍니다.

작업 그룹 모드 사용 가능
수집 Yes
로컬 컴퓨터 및 직접 형식 이름 Yes
원격 컴퓨터 No
원격 컴퓨터 및 직접 형식 이름 Yes

추가 정보

적용 대상

스레드 보안

메서드가 스레드로부터 안전하지 않습니다.