MessageQueue.Receive Metoda

Definicja

Odbiera pierwszy komunikat w kolejce, usuwając go z kolejki.

Przeciążenia

Receive()

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueueodwołuje się element . To wywołanie jest synchroniczne i blokuje bieżący wątek wykonywania do momentu udostępnienia komunikatu.

Receive(MessageQueueTransaction)

Odbiera pierwszy komunikat dostępny w kolejce transakcyjnej, do której odwołuje się element MessageQueue. To wywołanie jest synchroniczne i blokuje bieżący wątek wykonywania do momentu udostępnienia komunikatu.

Receive(MessageQueueTransactionType)

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueueodwołuje się element . To wywołanie jest synchroniczne i blokuje bieżący wątek wykonywania do momentu udostępnienia komunikatu.

Receive(TimeSpan)

Odbiera pierwszy komunikat dostępny w kolejce, do której odwołuje się MessageQueue element i czeka, aż komunikat będzie dostępny w kolejce lub upłynął limit czasu.

Receive(TimeSpan, Cursor)

Odbiera bieżący komunikat w kolejce przy użyciu określonego kursora. Jeśli komunikat nie jest dostępny, ta metoda czeka, aż komunikat będzie dostępny lub limit czasu wygaśnie.

Receive(TimeSpan, MessageQueueTransaction)

Odbiera pierwszy komunikat dostępny w kolejce transakcyjnej, do której odwołuje się MessageQueue element i czeka, aż komunikat będzie dostępny w kolejce lub limit czasu wygaśnie.

Receive(TimeSpan, MessageQueueTransactionType)

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueueodwołuje się element . To wywołanie jest synchroniczne i czeka na dostępność komunikatu w kolejce lub wygaśnięcie limitu czasu.

Receive(TimeSpan, Cursor, MessageQueueTransaction)

Odbiera bieżący komunikat w kolejce przy użyciu określonego kursora. Jeśli komunikat nie jest dostępny, ta metoda czeka, aż komunikat będzie dostępny lub limit czasu wygaśnie.

Receive(TimeSpan, Cursor, MessageQueueTransactionType)

Odbiera bieżący komunikat w kolejce przy użyciu określonego kursora. Jeśli komunikat nie jest dostępny, ta metoda czeka, aż komunikat będzie dostępny lub limit czasu wygaśnie.

Receive()

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueueodwołuje się element . To wywołanie jest synchroniczne i blokuje bieżący wątek wykonywania do momentu udostępnienia komunikatu.

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

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

Przykłady

Poniższy przykład kodu odbiera komunikat z kolejki i wyświetla informacje o tym komunikacie na ekranie.

#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:

   //*************************************************
   // 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;
   }

   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   void ReceiveMessage()
   {
      // Connect to the a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Set the formatter to indicate body contains an Order.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = Order::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );
      try
      {
         // Receive and format the message. 
         Message^ myMessage = myQueue->Receive();
         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 sends and receives a message from
// a queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

   // Receive a message from a queue.
   myNewQueue->ReceiveMessage();
   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 sends and receives a message from
        // a queue.
        //**************************************************

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

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

            // Receive a message from a queue.
            myNewQueue.ReceiveMessage();

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

        //**************************************************
        // Receives a message containing an Order.
        //**************************************************
        
        public  void ReceiveMessage()
        {
            // Connect to the a queue on the local computer.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");

            // Set the formatter to indicate body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(MyProject.Order)});
            
            try
            {
                // Receive and format the message.
                Message myMessage =	myQueue.Receive();
                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 receives 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 sends and receives a message from
        ' a qeue.
        '

        Public Shared Sub Main()

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

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

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessage()

            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


        '
        ' Receives a message containing an Order.
        '

        Public Sub ReceiveMessage()

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

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

            Try

                ' Receive and format the message. 
                Dim myMessage As Message = myQueue.Receive()
                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

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki lub oczekiwania na komunikaty w kolejce.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania metody będą zwracać Receive komunikaty, które następują w kolejce lub nowe komunikaty o wyższym priorytcie.

Aby odczytać pierwszy komunikat w kolejce bez usuwania go z kolejki, użyj Peek metody . Metoda Peek zawsze zwraca pierwszy komunikat w kolejce, dlatego kolejne wywołania metody zwracają ten sam komunikat, chyba że komunikat o wyższym priorytcie pojawi się w kolejce.

Użyj wywołania , aby Receive można było zablokować bieżący wątek podczas oczekiwania na nadejście komunikatu do kolejki. Ponieważ to przeciążenie Receive metody określa nieskończony limit czasu, aplikacja może czekać na czas nieokreślony. Jeśli przetwarzanie aplikacji powinno być kontynuowane bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Nazwa komputera lokalnego i bezpośredniego formatu Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i bezpośredniego formatu Tak

Zobacz też

Dotyczy

Receive(MessageQueueTransaction)

Odbiera pierwszy komunikat dostępny w kolejce transakcyjnej, do której odwołuje się element MessageQueue. To wywołanie jest synchroniczne i blokuje bieżący wątek wykonywania do momentu udostępnienia komunikatu.

public:
 System::Messaging::Message ^ Receive(System::Messaging::MessageQueueTransaction ^ transaction);
public System.Messaging.Message Receive (System.Messaging.MessageQueueTransaction transaction);
member this.Receive : System.Messaging.MessageQueueTransaction -> System.Messaging.Message
Public Function Receive (transaction As MessageQueueTransaction) As Message

Parametry

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

-lub-

Kolejka nie jest transakcyjna.

Przykłady

Poniższy przykład kodu łączy się z kolejką transakcyjną na komputerze lokalnym i wysyła komunikat do kolejki. Następnie otrzymuje komunikat zawierający zamówienie. Jeśli napotka kolejkę nie transakcyjną, zgłosi wyjątek i wycofa transakcję.

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

using namespace System;
using namespace System::Messaging;

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

   //*************************************************
   // Sends a message to a queue.
   //*************************************************
   void SendMessageTransactional()
   {
      // Connect to a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Send a message to the queue.
      if ( myQueue->Transactional == true )
      {
         // Create a transaction.
         MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;

         // Begin the transaction.
         myTransaction->Begin();

         // Send the message.
         myQueue->Send( "My Message Data.", myTransaction );

         // Commit the transaction.
         myTransaction->Commit();
      }

      return;
   }


   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   void ReceiveMessageTransactional()
   {
      // Connect to a transactional queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Set the formatter.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = String::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );

      // Create a transaction.
      MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;
      try
      {
         // Begin the transaction.
         myTransaction->Begin();

         // Receive the message. 
         Message^ myMessage = myQueue->Receive( myTransaction );
         String^ myOrder = static_cast<String^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( myOrder );

         // Commit the transaction.
         myTransaction->Commit();
      }
      catch ( MessageQueueException^ e ) 
      {
         // Handle nontransactional queues.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::TransactionUsage )
         {
            Console::WriteLine( "Queue is not transactional." );
         }

         // Else catch other sources of a MessageQueueException.
         // Roll back the transaction.
         myTransaction->Abort();
      }

      // Catch other exceptions as necessary, such as 
      // InvalidOperationException, thrown when the formatter 
      // cannot deserialize the message.
      return;
   }
};

//*************************************************
// Provides an entry point into the application.
// 
// This example sends and receives a message from
// a transactional queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

   // Receive a message from a queue.
   myNewQueue->ReceiveMessageTransactional();
   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 sends and receives a message from
        // a transactional queue.
        //**************************************************

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

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

            // Receive a message from a queue.
            myNewQueue.ReceiveMessageTransactional();

            return;
        }

        //**************************************************
        // Sends a message to a queue.
        //**************************************************
        
        public void SendMessageTransactional()
        {
                        
            // Connect to a queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Send a message to the queue.
            if (myQueue.Transactional == true)
            {
                // Create a transaction.
                MessageQueueTransaction myTransaction = new
                    MessageQueueTransaction();

                // Begin the transaction.
                myTransaction.Begin();

                // Send the message.
                myQueue.Send("My Message Data.", myTransaction);

                // Commit the transaction.
                myTransaction.Commit();
            }

            return;
        }

        //**************************************************
        // Receives a message containing an Order.
        //**************************************************
        
        public  void ReceiveMessageTransactional()
        {
            // Connect to a transactional queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Set the formatter.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});
            
            // Create a transaction.
            MessageQueueTransaction myTransaction = new
                MessageQueueTransaction();

            try
            {
                // Begin the transaction.
                myTransaction.Begin();
                
                // Receive the message.
                Message myMessage =	myQueue.Receive(myTransaction);
                String myOrder = (String)myMessage.Body;

                // Display message information.
                Console.WriteLine(myOrder);

                // Commit the transaction.
                myTransaction.Commit();
            }
            
            catch (MessageQueueException e)
            {
                // Handle nontransactional queues.
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.TransactionUsage)
                {
                    Console.WriteLine("Queue is not transactional.");
                }
                
                // Else catch other sources of a MessageQueueException.

                // Roll back the transaction.
                myTransaction.Abort();
            }

            // Catch other exceptions as necessary, such as
            // InvalidOperationException, thrown when the formatter
            // cannot deserialize the message.

            return;
        }
    }
}
Imports System.Messaging

Public Class MyNewQueue


        '
        ' Provides an entry point into the application.
        ' 
        ' This example sends and receives a message from
        ' a transactional queue.
        '

        Public Shared Sub Main()

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

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

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessageTransactional()

            Return

        End Sub


        '
        ' Sends a message to a queue.
        '

        Public Sub SendMessageTransactional()

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

            ' Send a message to the queue.
            If myQueue.Transactional = True Then

                ' Create a transaction.
                Dim myTransaction As New MessageQueueTransaction

                ' Begin the transaction.
                myTransaction.Begin()

                ' Send the message.
                myQueue.Send("My Message Data.", myTransaction)

                ' Commit the transaction.
                myTransaction.Commit()

            End If

            Return

        End Sub


        '
        ' Receives a message containing an Order.
        '

        Public Sub ReceiveMessageTransactional()

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

            ' Set the formatter.
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Create a transaction.
            Dim myTransaction As New MessageQueueTransaction

            Try

                ' Begin the transaction.
                myTransaction.Begin()

                ' Receive the message. 
                Dim myMessage As Message = _
                    myQueue.Receive(myTransaction)
                Dim myOrder As [String] = CType(myMessage.Body, _
                    [String])

                ' Display message information.
                Console.WriteLine(myOrder)

                ' Commit the transaction.
                myTransaction.Commit()


            Catch e As MessageQueueException

                ' Handle nontransactional queues.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.TransactionUsage Then

                    Console.WriteLine("Queue is not transactional.")

                End If

                ' Else catch other sources of a MessageQueueException.


                ' Roll back the transaction.
                myTransaction.Abort()


                ' Catch other exceptions as necessary, such as 
                ' InvalidOperationException, thrown when the formatter
                ' cannot deserialize the message.

            End Try

            Return

        End Sub

End Class

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki transakcyjnej przy użyciu wewnętrznego kontekstu transakcji zdefiniowanego transaction przez parametr lub zaczekaj na komunikaty w kolejce.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania polecenia Receive zwracają komunikaty, które następują w kolejce.

Ponieważ ta metoda jest wywoływana w kolejce transakcyjnej, odebrany komunikat zostanie zwrócony do kolejki, jeśli transakcja zostanie przerwana. Komunikat nie zostanie trwale usunięty z kolejki, dopóki transakcja nie zostanie zatwierdzona.

Aby odczytać pierwszy komunikat w kolejce bez usuwania go z kolejki, użyj Peek metody . Metoda Peek zawsze zwraca pierwszy komunikat w kolejce, dlatego kolejne wywołania metody zwracają ten sam komunikat, chyba że komunikat o wyższym priorytcie pojawi się w kolejce. Brak kontekstu transakcji skojarzonego z komunikatem zwróconym przez wywołanie metody Peek. Ponieważ Peek nie usuwa żadnych komunikatów w kolejce, nie byłoby nic do wycofywania przez wywołanie metody Abort.

Użyj wywołania , aby Receive można było zablokować bieżący wątek podczas oczekiwania na nadejście komunikatu do kolejki. Ponieważ to przeciążenie Receive metody określa nieskończony limit czasu, aplikacja może czekać na czas nieokreślony. Jeśli przetwarzanie aplikacji powinno być kontynuowane bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Nazwa komputera lokalnego i bezpośredniego formatu Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i bezpośredniego formatu Tak

Zobacz też

Dotyczy

Receive(MessageQueueTransactionType)

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueueodwołuje się element . To wywołanie jest synchroniczne i blokuje bieżący wątek wykonywania do momentu udostępnienia komunikatu.

public:
 System::Messaging::Message ^ Receive(System::Messaging::MessageQueueTransactionType transactionType);
public System.Messaging.Message Receive (System.Messaging.MessageQueueTransactionType transactionType);
member this.Receive : System.Messaging.MessageQueueTransactionType -> System.Messaging.Message
Public Function Receive (transactionType As MessageQueueTransactionType) As Message

Parametry

transactionType
MessageQueueTransactionType

MessageQueueTransactionType Jedna z wartości opisujących typ kontekstu transakcji do skojarzenia z komunikatem.

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

Parametr transactionType nie jest jednym z MessageQueueTransactionType elementów członkowskich.

Przykłady

W poniższym przykładzie kodu pokazano użycie metody Receive(MessageQueueTransactionType).


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

// Create a new message.
Message^ msg = gcnew Message("Example Message Body");

// Send the message.
queue->Send(msg, MessageQueueTransactionType::Single);

// Simulate doing other work so the message has time to arrive.
System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));

// Set the formatter to indicate the message body contains a String.
queue->Formatter = gcnew XmlMessageFormatter(
    gcnew array<Type^>{String::typeid});

// Receive the message from the queue.  Because the Id of the message
// , it might not be the message just sent.
msg = queue->Receive(MessageQueueTransactionType::Single);

queue->Close();

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

// Create a new message.
Message msg = new Message("Example Message Body");

// Send the message.
queue.Send(msg, MessageQueueTransactionType.Single);

// Simulate doing other work so the message has time to arrive.
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

// Set the formatter to indicate the message body contains a String.
queue.Formatter = new XmlMessageFormatter(new Type[]
    {typeof(String)});

// Receive the message from the queue.  Because the Id of the message
// , it might not be the message just sent.
msg = queue.Receive(MessageQueueTransactionType.Single);

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki przy użyciu kontekstu transakcji zdefiniowanego transactionType przez parametr lub zaczekaj na komunikaty w kolejce.

Określ Automatic parametr , transactionType jeśli istnieje już zewnętrzny kontekst transakcji dołączony do wątku, którego chcesz użyć do odbierania komunikatu. Określ Single , czy chcesz otrzymywać komunikat jako pojedynczą transakcję wewnętrzną. Możesz określić None , czy chcesz odbierać komunikat z kolejki transakcyjnej poza kontekstem transakcji.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania, które będą zwracać Receive komunikaty, które następują w kolejce.

Jeśli ta metoda jest wywoływana w celu odebrania komunikatu z kolejki transakcyjnej, komunikat, który zostanie odebrany, zostanie zwrócony do kolejki, jeśli transakcja zostanie przerwana. Komunikat nie zostanie trwale usunięty z kolejki, dopóki transakcja nie zostanie zatwierdzona.

Aby odczytać pierwszy komunikat w kolejce bez usunięcia go z kolejki, użyj Peek metody . Metoda Peek zawsze zwraca pierwszy komunikat w kolejce, więc kolejne wywołania metody zwracają ten sam komunikat, chyba że w kolejce pojawi się komunikat o wyższym priorytcie. Nie ma kontekstu transakcji skojarzonego z komunikatem zwróconym przez wywołanie metody Peek. Ponieważ Peek nie usuwa żadnych komunikatów w kolejce, nie byłoby nic do wycofania przez wywołanie metody Abort.

Użyj wywołania , aby można było zablokować Receive bieżący wątek podczas oczekiwania na przybycie komunikatu do kolejki. Ponieważ to przeciążenie Receive metody określa nieskończony limit czasu, aplikacja może czekać na czas nieokreślony. Jeśli przetwarzanie aplikacji powinno kontynuować bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Komputer lokalny i nazwa formatu bezpośredniego Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i formatu bezpośredniego Tak

Zobacz też

Dotyczy

Receive(TimeSpan)

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueue odwołuje się element i czeka, aż komunikat będzie dostępny w kolejce lub upłynął limit czasu.

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

Parametry

timeout
TimeSpan

Element TimeSpan wskazujący czas oczekiwania na udostępnienie nowej wiadomości do kontroli.

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wartość określona dla parametru timeout jest nieprawidłowa, prawdopodobnie timeout jest mniejsza lub większa niż ZeroInfiniteTimeout.

Komunikat nie dotarł do kolejki przed wygaśnięciem limitu czasu.

-lub-

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów

Przykłady

Poniższy przykład kodu odbiera komunikat z kolejki i wyświetla informacje o tym komunikacie na ekranie. Przykład wstrzymuje wykonywanie przez maksymalnie pięć sekund podczas oczekiwania na przybycie komunikatu do kolejki.

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

using namespace System;
using namespace System::Messaging;

// This class represents an object the following example 
// 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:

   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   void ReceiveMessage()
   {
      // Connect to the a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Set the formatter to indicate body contains an Order.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = Order::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );
      try
      {
         // Receive and format the message. 
         // Wait 5 seconds for a message to arrive.
         Message^ myMessage = myQueue->Receive( TimeSpan(0,0,5) );
         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^ e ) 
      {
         // Handle no message arriving in the queue.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            Console::WriteLine( "No message arrived in queue." );
         }

         // Handle other sources of a MessageQueueException.
      }
      // 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 receives a message from a queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

   // Receive a message from a queue.
   myNewQueue->ReceiveMessage();
   return 0;
}
using System;
using System.Messaging;

namespace MyProject
{
    // This class represents an object the following example
    // 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 receives a message from a queue.
        //**************************************************

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

            // Receive a message from a queue.
            myNewQueue.ReceiveMessage();

            return;
        }

        //**************************************************
        // Receives a message containing an Order.
        //**************************************************

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

            // Set the formatter to indicate body contains an Order.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(MyProject.Order)});
            
            try
            {
                // Receive and format the message.
                // Wait 5 seconds for a message to arrive.
                Message myMessage =	myQueue.Receive(new
                    TimeSpan(0,0,5));
                Order myOrder = (Order)myMessage.Body;

                // Display message information.
                Console.WriteLine("Order ID: " +
                    myOrder.orderId.ToString());
                Console.WriteLine("Sent: " +
                    myOrder.orderTime.ToString());
            }

            catch (MessageQueueException e)
            {
                // Handle no message arriving in the queue.
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine("No message arrived in queue.");
                }			

                // Handle other sources of a MessageQueueException.
            }
            
            // 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 
' receives 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 receives a message from a queue.
        '

        Public Shared Sub Main()

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

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessage()

            Return

        End Sub


        '
        ' Receives a message containing an Order.
        '

        Public Sub ReceiveMessage()

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

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

            Try

                ' Receive and format the message. 
                ' Wait 5 seconds for a message to arrive.
                Dim myMessage As Message = myQueue.Receive(New _
                    TimeSpan(0, 0, 5))
                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 e As MessageQueueException
                ' Handle no message arriving in the queue.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.IOTimeout Then

                    Console.WriteLine("No message arrived in queue.")

                End If

                ' Handle other sources of a MessageQueueException.

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

                ' Catch other exceptions as necessary.

            End Try

            Return

        End Sub

End Class

Uwagi

Użyj tego przeciążenia, aby odebrać komunikat i powrócić w określonym przedziale czasu, jeśli w kolejce nie ma żadnych komunikatów.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwanie go z kolejki. Kolejne wywołania, które będą zwracać Receive komunikaty, które następują w kolejce lub nowe komunikaty o wyższym priorytcie.

Aby odczytać pierwszy komunikat w kolejce bez usunięcia go z kolejki, użyj Peek metody . Metoda Peek zawsze zwraca pierwszy komunikat w kolejce, więc kolejne wywołania metody zwracają ten sam komunikat, chyba że w kolejce pojawi się komunikat o wyższym priorytcie.

Użyj wywołania , aby można było zablokować Receive bieżący wątek podczas oczekiwania na przybycie komunikatu do kolejki. Wątek zostanie zablokowany przez dany okres czasu lub na czas nieokreślony, jeśli określono wartość InfiniteTimeout parametru timeout . Jeśli przetwarzanie aplikacji powinno kontynuować bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Komputer lokalny i nazwa formatu bezpośredniego Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i formatu bezpośredniego Tak

Zobacz też

Dotyczy

Receive(TimeSpan, Cursor)

Odbiera bieżący komunikat w kolejce przy użyciu określonego kursora. Jeśli komunikat nie jest dostępny, ta metoda czeka na udostępnienie komunikatu lub upłynął limit czasu.

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

Parametry

timeout
TimeSpan

Element TimeSpan wskazujący czas oczekiwania na udostępnienie nowej wiadomości do kontroli.

cursor
Cursor

Element Cursor , który utrzymuje określoną pozycję w kolejce komunikatów.

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wartość określona dla parametru timeout jest nieprawidłowa, prawdopodobnie timeout jest mniejsza lub większa niż ZeroInfiniteTimeout.

Komunikat nie dotarł do kolejki przed wygaśnięciem limitu czasu.

-lub-

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów

Użyj tego przeciążenia, aby odebrać komunikat i powrócić w określonym przedziale czasu, jeśli w kolejce nie ma żadnych komunikatów.

Dotyczy

Receive(TimeSpan, MessageQueueTransaction)

Odbiera pierwszy komunikat dostępny w kolejce transakcyjnej, do której MessageQueue odwołuje się element i czeka, aż komunikat będzie dostępny w kolejce lub upłynął limit czasu.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::MessageQueueTransaction ^ transaction);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.MessageQueueTransaction transaction);
member this.Receive : TimeSpan * System.Messaging.MessageQueueTransaction -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, transaction As MessageQueueTransaction) As Message

Parametry

timeout
TimeSpan

Element TimeSpan wskazujący czas oczekiwania na udostępnienie nowej wiadomości do kontroli.

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wartość określona dla parametru timeout jest nieprawidłowa, prawdopodobnie timeout jest mniejsza lub większa niż ZeroInfiniteTimeout.

Komunikat nie dotarł do kolejki przed wygaśnięciem limitu czasu.

-lub-

Kolejka nie jest transakcyjna.

-lub-

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

Przykłady

Poniższy przykład kodu pokazuje użycie tej metody.

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

using namespace System;
using namespace System::Messaging;

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

   //*************************************************
   // Sends a message to a transactional queue.
   //*************************************************
   void SendMessageTransactional()
   {
      // Connect to a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Send a message to the queue.
      if ( myQueue->Transactional == true )
      {
         // Create a transaction.
         MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;

         // Begin the transaction.
         myTransaction->Begin();

         // Send the message.
         myQueue->Send( "My Message Data.", myTransaction );

         // Commit the transaction.
         myTransaction->Commit();
      }

      return;
   }

   //*************************************************
   // Receives a message from the transactional queue.
   //*************************************************
   void ReceiveMessageTransactional()
   {
      // Connect to a transactional queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myTransactionalQueue" );

      // Set the formatter.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = String::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );

      // Create a transaction.
      MessageQueueTransaction^ myTransaction = gcnew MessageQueueTransaction;
      try
      {
         // Begin the transaction.
         myTransaction->Begin();

         // Receive the message. 
         // Wait five seconds for a message to arrive. 
         Message^ myMessage = myQueue->Receive( TimeSpan(0,0,5), myTransaction );
         String^ myOrder = static_cast<String^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( myOrder );

         // Commit the transaction.
         myTransaction->Commit();
      }
      catch ( MessageQueueException^ e ) 
      {
         // Handle nontransactional queues.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::TransactionUsage )
         {
            Console::WriteLine( "Queue is not transactional." );
         }
         // Handle no message arriving in the queue.
         else

         // Handle no message arriving in the queue.
         if ( e->MessageQueueErrorCode == MessageQueueErrorCode::IOTimeout )
         {
            Console::WriteLine( "No message in queue." );
         }

         // Else catch other sources of MessageQueueException.
         // Roll back the transaction.
         myTransaction->Abort();
      }

      // Catch other exceptions as necessary, such as 
      // InvalidOperationException, thrown when the formatter 
      // cannot deserialize the message.
      return;
   }
};

//*************************************************
// Provides an entry point into the application.
// 
// This example sends and receives a message from
// a transactional queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

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

   // Receive a message from a queue.
   myNewQueue->ReceiveMessageTransactional();
   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 sends and receives a message from
        // a transactional queue.
        //**************************************************

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

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

            // Receive a message from a queue.
            myNewQueue.ReceiveMessageTransactional();

            return;
        }

        //**************************************************
        // Sends a message to a transactional queue.
        //**************************************************
        
        public void SendMessageTransactional()
        {
                        
            // Connect to a queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Send a message to the queue.
            if (myQueue.Transactional == true)
            {
                // Create a transaction.
                MessageQueueTransaction myTransaction = new
                    MessageQueueTransaction();

                // Begin the transaction.
                myTransaction.Begin();

                // Send the message.
                myQueue.Send("My Message Data.", myTransaction);

                // Commit the transaction.
                myTransaction.Commit();
            }

            return;
        }

        //**************************************************
        // Receives a message from the transactional queue.
        //**************************************************
        
        public  void ReceiveMessageTransactional()
        {
            // Connect to a transactional queue on the local computer.
            MessageQueue myQueue = new
                MessageQueue(".\\myTransactionalQueue");

            // Set the formatter.
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});
            
            // Create a transaction.
            MessageQueueTransaction myTransaction = new
                MessageQueueTransaction();

            try
            {
                // Begin the transaction.
                myTransaction.Begin();
                
                // Receive the message.
                // Wait five seconds for a message to arrive.
                Message myMessage =	myQueue.Receive(new
                    TimeSpan(0,0,5), myTransaction);
                
                String myOrder = (String)myMessage.Body;

                // Display message information.
                Console.WriteLine(myOrder);

                // Commit the transaction.
                myTransaction.Commit();
            }
            
            catch (MessageQueueException e)
            {
                // Handle nontransactional queues.
                if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.TransactionUsage)
                {
                    Console.WriteLine("Queue is not transactional.");
                }

                    // Handle no message arriving in the queue.
                else if (e.MessageQueueErrorCode ==
                    MessageQueueErrorCode.IOTimeout)
                {
                    Console.WriteLine("No message in queue.");
                }
                
                // Else catch other sources of MessageQueueException.

                // Roll back the transaction.
                myTransaction.Abort();
            }

            // Catch other exceptions as necessary, such as
            // InvalidOperationException, thrown when the formatter
            // cannot deserialize the message.

            return;
        }
    }
}
Imports System.Messaging

Namespace MyProj


   
    Public Class MyNewQueue


        '**************************************************
        ' Provides an entry point into the application.
        ' 
        ' This example sends and receives a message from
        ' a transactional queue.
        '**************************************************

        Public Shared Sub Main()

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

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

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessageTransactional()

            Return

        End Sub


        '**************************************************
        ' Sends a message to a transactional queue.
        '**************************************************

        Public Sub SendMessageTransactional()

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

            ' Send a message to the queue.
            If myQueue.Transactional = True Then

                ' Create a transaction.
                Dim myTransaction As New MessageQueueTransaction

                ' Begin the transaction.
                myTransaction.Begin()

                ' Send the message.
                myQueue.Send("My Message Data.", myTransaction)

                ' Commit the transaction.
                myTransaction.Commit()

            End If

            Return

        End Sub


        '**************************************************
        ' Receives a message from the transactional queue.
        '**************************************************

        Public Sub ReceiveMessageTransactional()

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

            ' Set the formatter.
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Create a transaction.
            Dim myTransaction As New MessageQueueTransaction

            Try

                ' Begin the transaction.
                myTransaction.Begin()

                ' Receive the message. 
                ' Wait five seconds for a message to arrive. 
                Dim myMessage As Message = myQueue.Receive(New _
                    TimeSpan(0, 0, 5), myTransaction)
                Dim myOrder As [String] = CType(myMessage.Body, _
                    [String])

                ' Display message information.
                Console.WriteLine(myOrder)

                ' Commit the transaction.
                myTransaction.Commit()


            Catch e As MessageQueueException

                ' Handle nontransactional queues.
                If e.MessageQueueErrorCode = _
                    MessageQueueErrorCode.TransactionUsage Then

                    Console.WriteLine("Queue is not transactional.")

                Else
                    ' Handle no message arriving in the queue.
                    If e.MessageQueueErrorCode = _
                        MessageQueueErrorCode.IOTimeout Then

                        Console.WriteLine("No message in queue.")

                    End If
                End If

                ' Else catch other sources of a MessageQueueException.

                ' Roll back the transaction.
                myTransaction.Abort()


                ' Catch other exceptions as necessary, such as InvalidOperationException,
                ' thrown when the formatter cannot deserialize the message.

            End Try

            Return

        End Sub

    End Class
End Namespace 'MyProj

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki transakcyjnej przy użyciu kontekstu transakcji wewnętrznej zdefiniowanej przez transaction parametr i zwracania w określonym przedziale czasu, jeśli w kolejce nie ma komunikatów.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania, które będą zwracać Receive komunikaty, które następują w kolejce.

Ponieważ ta metoda jest wywoływana w kolejce transakcyjnej, komunikat, który zostanie odebrany, zostanie zwrócony do kolejki, jeśli transakcja zostanie przerwana. Komunikat nie zostanie trwale usunięty z kolejki, dopóki transakcja nie zostanie zatwierdzona.

Aby odczytać pierwszy komunikat w kolejce bez usunięcia go z kolejki, użyj Peek metody . Metoda Peek zawsze zwraca pierwszy komunikat w kolejce, więc kolejne wywołania metody zwracają ten sam komunikat, chyba że w kolejce pojawi się komunikat o wyższym priorytcie. Nie ma kontekstu transakcji skojarzonego z komunikatem zwróconym przez wywołanie metody Peek. Ponieważ Peek nie usuwa żadnych komunikatów w kolejce, nie byłoby nic do wycofania przez wywołanie metody Abort.

Użyj wywołania , aby można było zablokować Receive bieżący wątek podczas oczekiwania na przybycie komunikatu do kolejki. Wątek zostanie zablokowany przez dany okres czasu lub na czas nieokreślony, jeśli określono wartość InfiniteTimeout parametru timeout . Jeśli przetwarzanie aplikacji powinno kontynuować bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Komputer lokalny i nazwa formatu bezpośredniego Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i formatu bezpośredniego Tak

Zobacz też

Dotyczy

Receive(TimeSpan, MessageQueueTransactionType)

Odbiera pierwszy komunikat dostępny w kolejce, do której MessageQueueodwołuje się element . To wywołanie jest synchroniczne i czeka na dostępność komunikatu w kolejce lub wygaśnięcie limitu czasu.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::MessageQueueTransactionType transactionType);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.MessageQueueTransactionType transactionType);
member this.Receive : TimeSpan * System.Messaging.MessageQueueTransactionType -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, transactionType As MessageQueueTransactionType) As Message

Parametry

timeout
TimeSpan

Element TimeSpan wskazujący czas oczekiwania na udostępnienie nowej wiadomości na potrzeby inspekcji.

transactionType
MessageQueueTransactionType

MessageQueueTransactionType Jedna z wartości opisujących typ kontekstu transakcji do skojarzenia z komunikatem.

Zwraca

Element Message odwołujący się do pierwszego komunikatu dostępnego w kolejce.

Wyjątki

Wartość określona dla parametru timeout jest nieprawidłowa, prawdopodobnie timeout jest mniejsza lub większa niż ZeroInfiniteTimeout.

Parametr transactionType nie jest jednym z MessageQueueTransactionType elementów członkowskich.

Komunikat nie dotarł do kolejki przed upływem limitu czasu.

-lub-

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

Przykłady

Poniższy przykład kodu pokazuje użycie tej metody.


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

// Create a new message.
Message^ msg = gcnew Message("Example Message Body");

// Send the message.
queue->Send(msg, MessageQueueTransactionType::Single);

// Set the formatter to indicate the message body contains a String.
queue->Formatter = gcnew XmlMessageFormatter(
    gcnew array<Type^>{String::typeid});

// Receive the message from the queue. Because the Id of the message
// is not specified, it might not be the message just sent.
msg = queue->Receive(TimeSpan::FromSeconds(10.0),
    MessageQueueTransactionType::Single);

queue->Close();

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

// Create a new message.
Message msg = new Message("Example Message Body");

// Send the message.
queue.Send(msg, MessageQueueTransactionType.Single);

// Set the formatter to indicate the message body contains a String.
queue.Formatter = new XmlMessageFormatter(new Type[]
    {typeof(String)});

// Receive the message from the queue. Because the Id of the message
// is not specified, it might not be the message just sent.
msg = queue.Receive(TimeSpan.FromSeconds(10.0),
    MessageQueueTransactionType.Single);

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki przy użyciu kontekstu transakcji zdefiniowanego przez transactionType parametr i zwracania w określonym przedziale czasu, jeśli w kolejce nie ma komunikatów.

Określ Automatic parametr , transactionType jeśli istnieje już zewnętrzny kontekst transakcji dołączony do wątku, którego chcesz użyć do odbierania komunikatu. Określ Single , czy chcesz otrzymywać komunikat jako pojedynczą transakcję wewnętrzną. Możesz określić None , czy chcesz odbierać komunikat z kolejki transakcyjnej poza kontekstem transakcji.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania polecenia Receive zwracają komunikaty, które następują w kolejce.

Jeśli ta metoda jest wywoływana w celu odbierania komunikatu z kolejki transakcyjnej, odebrany komunikat zostanie zwrócony do kolejki, jeśli transakcja zostanie przerwana. Komunikat nie zostanie trwale usunięty z kolejki, dopóki transakcja nie zostanie zatwierdzona.

Aby odczytać pierwszy komunikat w kolejce bez usuwania go z kolejki, użyj Peek metody . Metoda Peek zawsze zwraca pierwszy komunikat w kolejce, dlatego kolejne wywołania metody zwracają ten sam komunikat, chyba że komunikat o wyższym priorytcie pojawi się w kolejce. Brak kontekstu transakcji skojarzonego z komunikatem zwróconym przez wywołanie metody Peek. Ponieważ Peek nie usuwa żadnych komunikatów w kolejce, nie byłoby nic do wycofywania przez wywołanie metody Abort.

Użyj wywołania , aby Receive można było zablokować bieżący wątek podczas oczekiwania na nadejście komunikatu do kolejki. Wątek zostanie zablokowany przez dany okres lub na czas nieokreślony, jeśli określono wartość InfiniteTimeout parametru timeout . Jeśli przetwarzanie aplikacji powinno być kontynuowane bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Nazwa komputera lokalnego i bezpośredniego formatu Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i bezpośredniego formatu Tak

Zobacz też

Dotyczy

Receive(TimeSpan, Cursor, MessageQueueTransaction)

Odbiera bieżący komunikat w kolejce przy użyciu określonego kursora. Jeśli komunikat nie jest dostępny, ta metoda czeka, aż komunikat będzie dostępny lub limit czasu wygaśnie.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Messaging::MessageQueueTransaction ^ transaction);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.MessageQueueTransaction transaction);
member this.Receive : TimeSpan * System.Messaging.Cursor * System.Messaging.MessageQueueTransaction -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, cursor As Cursor, transaction As MessageQueueTransaction) As Message

Parametry

timeout
TimeSpan

Element TimeSpan wskazujący czas oczekiwania na udostępnienie nowej wiadomości na potrzeby inspekcji.

cursor
Cursor

Element Cursor , który utrzymuje określoną pozycję w kolejce komunikatów.

Zwraca

Element Message , który odwołuje się do komunikatu w kolejce.

Wyjątki

Parametr cursor ma wartość null.

-lub-

Parametr transaction ma wartość null.

Wartość określona dla parametru timeout jest nieprawidłowa. Prawdopodobnie timeout wartość jest mniejsza lub większa niż InfiniteTimeoutZero .

Komunikat nie dotarł do kolejki przed upływem limitu czasu.

-lub-

Kolejka nie jest transakcyjna.

-lub-

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki transakcyjnej przy użyciu wewnętrznego kontekstu transakcji zdefiniowanego przez transaction parametr i zwracania w określonym przedziale czasu, jeśli w kolejce nie ma komunikatów.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania w celu Receive zwrócenia komunikatów, które następują w kolejce.

Ponieważ ta metoda jest wywoływana w kolejce transakcyjnej, odebrany komunikat jest zwracany do kolejki, jeśli transakcja została przerwana. Komunikat nie zostanie trwale usunięty z kolejki, dopóki transakcja nie zostanie zatwierdzona.

Aby odczytać komunikat w kolejce bez usuwania go z kolejki, użyj Peek metody . Brak kontekstu transakcji skojarzonego z komunikatem zwróconym przez wywołanie metody Peek. Ponieważ Peek nie usuwa żadnych komunikatów w kolejce, nie ma nic do wycofywania przez wywołanie metody Abort.

Użyj wywołania , aby Receive można było zablokować bieżący wątek podczas oczekiwania na nadejście komunikatu do kolejki. Wątek jest blokowany przez dany okres czasu lub na czas nieokreślony, jeśli określono wartość InfiniteTimeout parametru timeout . Jeśli przetwarzanie aplikacji powinno być kontynuowane bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Nazwa komputera lokalnego i bezpośredniego formatu Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i bezpośredniego formatu Tak

Zobacz też

Dotyczy

Receive(TimeSpan, Cursor, MessageQueueTransactionType)

Odbiera bieżący komunikat w kolejce przy użyciu określonego kursora. Jeśli komunikat nie jest dostępny, ta metoda czeka, aż komunikat będzie dostępny lub limit czasu wygaśnie.

public:
 System::Messaging::Message ^ Receive(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Messaging::MessageQueueTransactionType transactionType);
public System.Messaging.Message Receive (TimeSpan timeout, System.Messaging.Cursor cursor, System.Messaging.MessageQueueTransactionType transactionType);
member this.Receive : TimeSpan * System.Messaging.Cursor * System.Messaging.MessageQueueTransactionType -> System.Messaging.Message
Public Function Receive (timeout As TimeSpan, cursor As Cursor, transactionType As MessageQueueTransactionType) As Message

Parametry

timeout
TimeSpan

Element TimeSpan wskazujący czas oczekiwania na udostępnienie nowej wiadomości na potrzeby inspekcji.

cursor
Cursor

Element Cursor , który utrzymuje określoną pozycję w kolejce komunikatów.

transactionType
MessageQueueTransactionType

MessageQueueTransactionType Jedna z wartości opisujących typ kontekstu transakcji do skojarzenia z komunikatem.

Zwraca

Element Message , który odwołuje się do komunikatu w kolejce.

Wyjątki

Parametr cursor ma wartość null.

Wartość określona dla parametru timeout jest nieprawidłowa. Prawdopodobnie timeout wartość jest mniejsza lub większa niż InfiniteTimeoutZero .

Parametr transactionType nie jest jednym z MessageQueueTransactionType elementów członkowskich.

Komunikat nie dotarł do kolejki przed upływem limitu czasu.

-lub-

Wystąpił błąd podczas uzyskiwania dostępu do metody kolejkowania komunikatów.

Uwagi

To przeciążenie służy do odbierania komunikatu z kolejki przy użyciu kontekstu transakcji zdefiniowanego przez transactionType parametr i zwracania w określonym przedziale czasu, jeśli w kolejce nie ma komunikatów.

Określ Automatic parametr , transactionType jeśli istnieje już zewnętrzny kontekst transakcji dołączony do wątku, którego chcesz użyć do odbierania komunikatu. Określ Single , czy chcesz otrzymywać komunikat jako pojedynczą transakcję wewnętrzną. Możesz określić None , czy chcesz odbierać komunikat z kolejki transakcyjnej poza kontekstem transakcji.

Metoda Receive umożliwia synchroniczne odczytywanie komunikatu, usuwając go z kolejki. Kolejne wywołania w celu Receive zwrócenia komunikatów, które następują w kolejce.

Jeśli ta metoda jest wywoływana w celu odbierania komunikatu z kolejki transakcyjnej, odebrany komunikat jest zwracany do kolejki, jeśli transakcja zostanie przerwana. Komunikat nie zostanie trwale usunięty z kolejki, dopóki transakcja nie zostanie zatwierdzona.

Aby odczytać komunikat w kolejce bez usuwania go z kolejki, użyj Peek metody . Brak kontekstu transakcji skojarzonego z komunikatem zwróconym przez wywołanie metody Peek. Ponieważ Peek nie usuwa żadnych komunikatów w kolejce, nie ma nic do wycofywania przez wywołanie metody Abort.

Użyj wywołania , aby Receive można było zablokować bieżący wątek podczas oczekiwania na nadejście komunikatu do kolejki. Wątek jest blokowany przez dany okres czasu lub na czas nieokreślony, jeśli określono wartość InfiniteTimeout parametru timeout . Jeśli przetwarzanie aplikacji powinno być kontynuowane bez oczekiwania na komunikat, rozważ użycie metody asynchronicznej . BeginReceive

W poniższej tabeli przedstawiono, czy ta metoda jest dostępna w różnych trybach grupy roboczej.

Tryb grupy roboczej Dostępne
Komputer lokalny Tak
Nazwa komputera lokalnego i bezpośredniego formatu Tak
Komputer zdalny Nie
Nazwa komputera zdalnego i bezpośredniego formatu Tak

Zobacz też

Dotyczy

Bezpieczeństwo wątkowe

Metoda nie jest bezpieczna wątkiem.