MessageQueue.BeginReceive Metodo

Definizione

Avvia un'operazione di ricezione asincrona, indicando ad Accodamento messaggi di avviare la ricezione di un messaggio e inviare una notifica al gestore eventi al termine dell'operazione.

Overload

BeginReceive()

Avvia un'operazione di ricezione asincrona senza timeout. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda.

BeginReceive(TimeSpan)

Avvia un'operazione di ricezione asincrona con un timeout specificato. L'operazione non viene completata fino a quando non viene reso disponibile un messaggio nella coda o si verifica il timeout.

BeginReceive(TimeSpan, Object)

Avvia un'operazione di ricezione asincrona per la quale sono stati specificati un timeout e un oggetto di stato, che fornisce le informazioni associate per tutta la durata dell'operazione. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda o non si verifica il timeout.

BeginReceive(TimeSpan, Object, AsyncCallback)

Avvia un'operazione di ricezione asincrona per la quale sono stati specificati un timeout e un oggetto di stato, che fornisce le informazioni associate per tutta la durata dell'operazione. Questo overload riceve mediante un callback la notifica dell'identità del gestore eventi per l'operazione. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda o non si verifica il timeout.

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

Avvia un'operazione di ricezione asincrona che presenta il timeout specificato e che utilizza il cursore specificato, l'azione di lettura specificata e l'oggetto di stato specificato. L'oggetto di stato fornisce informazioni associate per l'intera durata dell'operazione. Questo overload riceve mediante un callback la notifica dell'identità del gestore eventi per l'operazione. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda o non si verifica il timeout.

BeginReceive()

Avvia un'operazione di ricezione asincrona senza timeout. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda.

public:
 IAsyncResult ^ BeginReceive();
public IAsyncResult BeginReceive ();
member this.BeginReceive : unit -> IAsyncResult
Public Function BeginReceive () As IAsyncResult

Restituisce

IAsyncResult che identifica la richiesta asincrona inviata.

Eccezioni

Si è verificato un errore durante l'accesso a un metodo di Accodamento messaggi.

Esempio

L'esempio di codice seguente concatena le richieste asincrone. Si presuppone che nel computer locale sia presente una coda denominata "myQueue". La Main funzione avvia l'operazione asincrona gestita dalla MyReceiveCompleted routine. MyReceiveCompleted elabora il messaggio corrente e avvia una nuova operazione di ricezione asincrona.

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

using namespace System;
using namespace System::Messaging;
using namespace System::Threading;

ref class MyNewQueue
{
public:

   // Define static class members.
   static ManualResetEvent^ signal = gcnew ManualResetEvent( false );
   static int count = 0;

   // Provides an event handler for the ReceiveCompleted
   // event.
   static void MyReceiveCompleted( Object^ source, ReceiveCompletedEventArgs^ asyncResult )
   {
      try
      {
         // Connect to the queue.
         MessageQueue^ mq = dynamic_cast<MessageQueue^>(source);

         // End the asynchronous receive operation.
         mq->EndReceive( asyncResult->AsyncResult );
         count += 1;
         if ( count == 10 )
         {
            signal->Set();
         }

         // Restart the asynchronous receive operation.
         mq->BeginReceive();
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle sources of MessageQueueException.
      }

      // Handle other exceptions.
      return;
   }
};

// Provides an entry point into the application.
//         
// This example performs asynchronous receive
// operation processing.
int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the ReceiveCompleted event.
   myQueue->ReceiveCompleted += gcnew ReceiveCompletedEventHandler( MyNewQueue::MyReceiveCompleted );

   // Begin the asynchronous receive operation.
   myQueue->BeginReceive();
   MyNewQueue::signal->WaitOne();

   // Do other work on the current thread.
   return 0;
}
using System;
using System.Messaging;
using System.Threading;

namespace MyProject
{
    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue
    {
        // Define static class members.
        static ManualResetEvent signal = new ManualResetEvent(false);
        static int count = 0;

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example performs asynchronous receive
        // operation processing.
        //**************************************************

        public static void Main()
        {
            // Create an instance of MessageQueue. Set its formatter.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});

            // Add an event handler for the ReceiveCompleted event.
            myQueue.ReceiveCompleted +=
                new ReceiveCompletedEventHandler(MyReceiveCompleted);
            
            // Begin the asynchronous receive operation.
            myQueue.BeginReceive();

            signal.WaitOne();
            
            // Do other work on the current thread.

            return;
        }

        //***************************************************
        // Provides an event handler for the ReceiveCompleted
        // event.
        //***************************************************
        
        private static void MyReceiveCompleted(Object source,
            ReceiveCompletedEventArgs asyncResult)
        {
            try
            {
                // Connect to the queue.
                MessageQueue mq = (MessageQueue)source;

                // End the asynchronous receive operation.
                Message m = mq.EndReceive(asyncResult.AsyncResult);
                
                count += 1;
                if (count == 10)
                {
                    signal.Set();
                }

                // Restart the asynchronous receive operation.
                mq.BeginReceive();
            }
            catch(MessageQueueException)
            {
                // Handle sources of MessageQueueException.
            }
            
            // Handle other exceptions.
            
            return;
        }
    }
}
Imports System.Messaging
Imports System.Threading




' Provides a container class for the example.

Public Class MyNewQueue

        ' Define static class members.
        Private Shared signal As New ManualResetEvent(False)
        Private Shared count As Integer = 0



        ' Provides an entry point into the application.
        '		 
        ' This example performs asynchronous receive
        ' operation processing.


        Public Shared Sub Main()
            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Add an event handler for the ReceiveCompleted event.
            AddHandler myQueue.ReceiveCompleted, AddressOf _
                MyReceiveCompleted

            ' Begin the asynchronous receive operation.
            myQueue.BeginReceive()

            signal.WaitOne()

            ' Do other work on the current thread.

            Return

        End Sub



        ' Provides an event handler for the ReceiveCompleted
        ' event.


        Private Shared Sub MyReceiveCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As ReceiveCompletedEventArgs)

            Try
                ' Connect to the queue.
                Dim mq As MessageQueue = CType([source], MessageQueue)

                ' End the asynchronous receive operation.
                Dim m As Message = _
                    mq.EndReceive(asyncResult.AsyncResult)

                count += 1
                If count = 10 Then
                    signal.Set()
                End If

                ' Restart the asynchronous receive operation.
                mq.BeginReceive()

            Catch
                ' Handle sources of MessageQueueException.

                ' Handle other exceptions.

            End Try

            Return

        End Sub

End Class

L'esempio di codice seguente accoda le richieste asincrone. La chiamata a BeginReceive utilizza l'oggetto AsyncWaitHandle nel relativo valore restituito. La Main routine attende il completamento di tutte le operazioni asincrone prima dell'uscita.

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

using namespace System;
using namespace System::Messaging;
using namespace System::Threading;

ref class MyNewQueue
{
public:

   // Provides an event handler for the ReceiveCompleted
   // event.
   static void MyReceiveCompleted( Object^ source, ReceiveCompletedEventArgs^ asyncResult )
   {
      try
      {
         // Connect to the queue.
         MessageQueue^ mq = dynamic_cast<MessageQueue^>(source);

         // End the asynchronous receive operation.
         mq->EndReceive( asyncResult->AsyncResult );

         // Process the message here.
         Console::WriteLine( "Message received." );
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle sources of MessageQueueException.
      }
      // Handle other exceptions.
      return;
   }
};

// Provides an entry point into the application.
//         
// This example performs asynchronous receive
// operation processing.
int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the ReceiveCompleted event.
   myQueue->ReceiveCompleted += gcnew ReceiveCompletedEventHandler( MyNewQueue::MyReceiveCompleted );

   // Define wait handles for multiple operations.
   array<WaitHandle^>^waitHandleArray = gcnew array<WaitHandle^>(10);
   for ( int i = 0; i < 10; i++ )
   {
      // Begin asynchronous operations.
      waitHandleArray[ i ] = myQueue->BeginReceive()->AsyncWaitHandle;
   }

   // Specify to wait for all operations to return.
   WaitHandle::WaitAll( waitHandleArray );
   return 0;
}
using System;
using System.Messaging;
using System.Threading;

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

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example performs asynchronous receive
        // operation processing.
        //**************************************************

        public static void Main()
        {
            // Create an instance of MessageQueue. Set its formatter.
            MessageQueue myQueue = new MessageQueue(".\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});

            // Add an event handler for the ReceiveCompleted event.
            myQueue.ReceiveCompleted +=
                new ReceiveCompletedEventHandler(MyReceiveCompleted);
            
            // Define wait handles for multiple operations.
            WaitHandle[] waitHandleArray = new WaitHandle[10];
            for(int i=0; i<10; i++)
            {
                // Begin asynchronous operations.
                waitHandleArray[i] =
                    myQueue.BeginReceive().AsyncWaitHandle;
            }

            // Specify to wait for all operations to return.
            WaitHandle.WaitAll(waitHandleArray);

            return;
        }

        //***************************************************
        // Provides an event handler for the ReceiveCompleted
        // event.
        //***************************************************
        
        private static void MyReceiveCompleted(Object source,
            ReceiveCompletedEventArgs asyncResult)
        {
            try
            {
                // Connect to the queue.
                MessageQueue mq = (MessageQueue)source;

                // End the asynchronous receive operation.
                Message m = mq.EndReceive(asyncResult.AsyncResult);
        
                // Process the message here.
                Console.WriteLine("Message received.");
            }
            catch(MessageQueueException)
            {
                // Handle sources of MessageQueueException.
            }
            
            // Handle other exceptions.
            
            return;
        }
    }
}
Imports System.Messaging
Imports System.Threading


' Provides a container class for the example.

Public Class MyNewQueue


        ' Provides an entry point into the application.
        '		 
        ' This example performs asynchronous receive
        ' operation processing.


        Public Shared Sub Main()

            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Add an event handler for the ReceiveCompleted event.
            AddHandler myQueue.ReceiveCompleted, AddressOf _
                MyReceiveCompleted

            ' Define wait handles for multiple operations.
            Dim waitHandleArray(10) As WaitHandle

            Dim i As Integer
            For i = 0 To 9
                ' Begin asynchronous operations.
                waitHandleArray(i) = _
                    myQueue.BeginReceive().AsyncWaitHandle
            Next i

            ' Specify to wait for all operations to return.
            WaitHandle.WaitAll(waitHandleArray)

            Return

        End Sub



        ' Provides an event handler for the ReceiveCompleted
        ' event.


        Private Shared Sub MyReceiveCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As ReceiveCompletedEventArgs)

            Try
                ' Connect to the queue.
                Dim mq As MessageQueue = CType([source], MessageQueue)

                ' End the asynchronous receive operation.
                Dim m As Message = _
                    mq.EndReceive(asyncResult.AsyncResult)

                ' Process the message here.
                Console.WriteLine("Message received.")

            Catch

                ' Handle sources of MessageQueueException.

                ' Handle other exceptions.

            End Try

            Return

        End Sub

End Class

Commenti

Nell'elaborazione asincrona si usa BeginReceive per generare l'evento ReceiveCompleted quando un messaggio è stato rimosso dalla coda.

ReceiveCompleted viene generato anche se nella coda esiste già un messaggio.

Per usare BeginReceive, creare un gestore eventi che elabora i risultati dell'operazione asincrona e associarlo al delegato dell'evento. BeginReceive avvia un'operazione di ricezione asincrona; l'oggetto MessageQueue riceve una notifica, tramite la generazione dell'evento ReceiveCompleted , quando un messaggio arriva nella coda. L'oggetto MessageQueue può quindi accedere al messaggio chiamando EndReceive(IAsyncResult).

Il BeginReceive metodo restituisce immediatamente, ma l'operazione asincrona non viene completata fino a quando non viene chiamato il gestore eventi.

Poiché BeginReceive è asincrono, è possibile chiamarlo per ricevere un messaggio dalla coda senza bloccare il thread corrente di esecuzione. Per ricevere in modo sincrono un messaggio, usare il Receive metodo .

Al termine di un'operazione asincrona, è possibile chiamare BeginPeek o BeginReceive di nuovo nel gestore eventi per mantenere la ricezione delle notifiche.

Oggetto IAsyncResult che BeginReceive restituisce identifica l'operazione asincrona avviata dal metodo. È possibile usarlo IAsyncResult per tutta la durata dell'operazione, anche se in genere non viene usato fino a EndReceive(IAsyncResult) quando non viene chiamato. Tuttavia, se si avviano diverse operazioni asincrone, è possibile posizionarne IAsyncResult i valori in una matrice e specificare se attendere il completamento di tutte le operazioni o qualsiasi operazione. In questo caso, si usa la AsyncWaitHandle proprietà di IAsyncResult per identificare l'operazione completata.

Se CanRead è false, viene generato l'evento di completamento, ma viene generata un'eccezione quando si chiama EndReceive(IAsyncResult).

Non usare la chiamata BeginReceive asincrona con le transazioni. Se si vuole eseguire un'operazione asincrona transazionale, chiamare BeginPeeke inserire la transazione e il metodo (sincrono) Receive all'interno del gestore eventi creato per l'operazione di visualizzazione. Il gestore eventi potrebbe contenere funzionalità come illustrato nel codice C# seguente.

myMessageQueue.BeginTransaction();
 myMessageQueue.Receive();
 myMessageQueue.CommitTransaction();

Nella tabella seguente viene illustrato se questo metodo è disponibile in varie modalità gruppo di lavoro.

Modalità gruppo di lavoro Disponibile
Computer locale
Computer locale e nome del formato diretto
Computer remoto No
Nome del formato diretto e del computer remoto

Vedi anche

Si applica a

BeginReceive(TimeSpan)

Avvia un'operazione di ricezione asincrona con un timeout specificato. L'operazione non viene completata fino a quando non viene reso disponibile un messaggio nella coda o si verifica il timeout.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout);
public IAsyncResult BeginReceive (TimeSpan timeout);
member this.BeginReceive : TimeSpan -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan) As IAsyncResult

Parametri

timeout
TimeSpan

Oggetto TimeSpan che indica il tempo di attesa necessario affinché un messaggio diventi disponibile.

Restituisce

IAsyncResult che identifica la richiesta asincrona inviata.

Eccezioni

Il valore specificato per il parametro timeout non è valido, probabilmente perché rappresenta un numero negativo.

Si è verificato un errore durante l'accesso a un metodo di Accodamento messaggi.

Esempio

Nell'esempio di codice seguente viene creata un'operazione di ricezione asincrona. L'esempio di codice crea un gestore eventi, MyReceiveCompleted, e lo associa al delegato del ReceiveCompleted gestore eventi. L'esempio di codice invia un messaggio a una coda di messaggi locale, quindi chiama BeginReceive(TimeSpan), passando un valore di timeout di dieci secondi. Quando viene generato un ReceiveCompleted evento, il gestore eventi riceve il messaggio e scrive il corpo del messaggio nella schermata.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if(!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();       
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the ReceiveCompleted event.
void HandleReceiveCompleted(Object^ source, ReceiveCompletedEventArgs^ e)
{
    // Connect to the queue.
    MessageQueue^ queue = (MessageQueue^)source;

    // End the asynchronous receive operation.
    Message^ msg = queue->EndReceive(e->AsyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message body: {0}", msg->Body);
    
    queue->Close();
}

int main()
{
    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    MessageQueue^ queue = nullptr;
    try
    {
        CreateQueue(".\\exampleQueue", false);

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

        // Add an event handler for the ReceiveCompleted event.
        queue->ReceiveCompleted += gcnew
            ReceiveCompletedEventHandler(HandleReceiveCompleted);

        // Send a message to the queue.
        queue->Send("Example Message");

        // Begin the asynchronous receive operation.
        queue->BeginReceive(TimeSpan::FromSeconds(10.0));

        // Simulate doing other work on the current thread.
        System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));
    }

    catch (InvalidOperationException^)
    {
        Console::WriteLine("Please install Message Queuing.");
    }

    catch (MessageQueueException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    finally
    {   
        queue->Close();
    }

}

using System;
using System.Messaging;

public class QueueExample
{
    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

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

        // Add an event handler for the ReceiveCompleted event.
        queue.ReceiveCompleted += new
                ReceiveCompletedEventHandler(MyReceiveCompleted);

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous receive operation.
        queue.BeginReceive(TimeSpan.FromSeconds(10.0));

        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

    // Provides an event handler for the ReceiveCompleted event.
    private static void MyReceiveCompleted(Object source,
        ReceiveCompletedEventArgs asyncResult)
    {
        // Connect to the queue.
        MessageQueue queue = (MessageQueue)source;

        // End the asynchronous receive operation.
        Message msg = queue.EndReceive(asyncResult.AsyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message body: {0}", (string)msg.Body);
    }
}

Commenti

Nell'elaborazione asincrona si usa BeginReceive per generare l'evento ReceiveCompleted quando un messaggio diventa disponibile nella coda o quando è scaduto l'intervallo di tempo specificato.

ReceiveCompleted viene generato anche se nella coda esiste già un messaggio.

Per usare BeginReceive, creare un gestore eventi che elabora i risultati dell'operazione asincrona e associarlo al delegato dell'evento. BeginReceive avvia un'operazione di ricezione asincrona; l'oggetto MessageQueue riceve una notifica, tramite la generazione dell'evento ReceiveCompleted , quando un messaggio arriva nella coda. Può MessageQueue quindi accedere al messaggio chiamando EndReceive(IAsyncResult) o recuperando il risultato usando .ReceiveCompletedEventArgs

Il BeginReceive metodo restituisce immediatamente, ma l'operazione asincrona non viene completata fino a quando non viene chiamato il gestore eventi.

Poiché BeginReceive è asincrono, è possibile chiamarlo per ricevere un messaggio dalla coda senza bloccare il thread corrente di esecuzione. Per ricevere in modo sincrono un messaggio, usare il Receive metodo .

Al termine di un'operazione asincrona, è possibile chiamare BeginPeek o BeginReceive di nuovo nel gestore eventi per mantenere la ricezione delle notifiche.

Se CanRead è false, viene generato l'evento di completamento, ma viene generata un'eccezione quando si chiama EndReceive(IAsyncResult).

Oggetto IAsyncResult che BeginReceive restituisce identifica l'operazione asincrona avviata dal metodo. È possibile usarlo IAsyncResult per tutta la durata dell'operazione, anche se in genere non viene usato fino a EndReceive(IAsyncResult) quando non viene chiamato. Tuttavia, se si avviano diverse operazioni asincrone, è possibile posizionarne IAsyncResult i valori in una matrice e specificare se attendere il completamento di tutte le operazioni o qualsiasi operazione. In questo caso, si usa la AsyncWaitHandle proprietà di IAsyncResult per identificare l'operazione completata.

Questo overload specifica un timeout. Se l'intervallo specificato dal timeout parametro scade, questo componente genera l'evento ReceiveCompleted . Poiché non esiste alcun messaggio, una chiamata successiva a EndReceive(IAsyncResult) genererà un'eccezione.

Non usare la chiamata BeginReceive asincrona con le transazioni. Se si vuole eseguire un'operazione asincrona transazionale, chiamare BeginPeeke inserire la transazione e il metodo (sincrono) Receive all'interno del gestore eventi creato per l'operazione di visualizzazione. Il gestore eventi potrebbe contenere funzionalità come illustrato nel codice C# seguente.

myMessageQueue.BeginTransaction();
 myMessageQueue.Receive();
 myMessageQueue.CommitTransaction();

Nella tabella seguente viene illustrato se questo metodo è disponibile in varie modalità gruppo di lavoro.

Modalità gruppo di lavoro Disponibile
Computer locale
Computer locale e nome del formato diretto
Computer remoto No
Nome del formato diretto e del computer remoto

Vedi anche

Si applica a

BeginReceive(TimeSpan, Object)

Avvia un'operazione di ricezione asincrona per la quale sono stati specificati un timeout e un oggetto di stato, che fornisce le informazioni associate per tutta la durata dell'operazione. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda o non si verifica il timeout.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout, System::Object ^ stateObject);
public IAsyncResult BeginReceive (TimeSpan timeout, object stateObject);
member this.BeginReceive : TimeSpan * obj -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan, stateObject As Object) As IAsyncResult

Parametri

timeout
TimeSpan

Oggetto TimeSpan che indica il tempo di attesa necessario affinché un messaggio diventi disponibile.

stateObject
Object

Oggetto di stato, specificato dall'applicazione, che contiene le informazioni associate all'operazione asincrona.

Restituisce

IAsyncResult che identifica la richiesta asincrona inviata.

Eccezioni

Il valore specificato per il parametro timeout non è valido.

Si è verificato un errore durante l'accesso a un metodo di Accodamento messaggi.

Esempio

Nell'esempio di codice seguente viene creata un'operazione di ricezione asincrona. L'esempio di codice crea un gestore eventi, MyReceiveCompleted, e lo associa al delegato del ReceiveCompleted gestore eventi. L'esempio di codice invia un messaggio a una coda di messaggi locale, quindi chiama BeginReceive(TimeSpan, Object), passando un valore di timeout di dieci secondi e un numero intero univoco che identifica tale messaggio specifico. Quando viene generato un ReceiveCompleted evento, il gestore eventi riceve il messaggio e scrive il corpo del messaggio e l'identificatore di messaggio intero nella schermata.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if(!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();       
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the ReceiveCompleted event.
void HandleReceiveCompleted(Object^ source, ReceiveCompletedEventArgs^ e)
{
    // Connect to the queue.
    MessageQueue^ queue = (MessageQueue^)source;

    // End the asynchronous receive operation.
    Message^ msg = queue->EndReceive(e->AsyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message number: {0}", e->AsyncResult->AsyncState);
    Console::WriteLine("Message body: {0}", msg->Body);

    queue->Close();
}

int main()
{
    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    MessageQueue^ queue = nullptr;

    // Represents a state object associated with each message.
    int messageNumber = 0;

    try
    {
        CreateQueue(".\\exampleQueue", false);

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

        // Add an event handler for the ReceiveCompleted event.
        queue->ReceiveCompleted += gcnew
            ReceiveCompletedEventHandler(HandleReceiveCompleted);

        // Send a message to the queue.
        queue->Send("Example Message");

        // Begin the asynchronous receive operation.
        queue->BeginReceive(TimeSpan::FromSeconds(10.0), messageNumber++);

        // Simulate doing other work on the current thread.
        System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));
    }
    catch (InvalidOperationException^)
    {
        Console::WriteLine("Please install Message Queuing.");
    }

    catch (MessageQueueException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    finally
    {   
        queue->Close();
    }
}

using System;
using System.Messaging;

public class QueueExample
{
    // Represents a state object associated with each message.
    static int messageNumber = 0;

    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

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

        // Add an event handler for the ReceiveCompleted event.
        queue.ReceiveCompleted += new
            ReceiveCompletedEventHandler(MyReceiveCompleted);

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous receive operation.
        queue.BeginReceive(TimeSpan.FromSeconds(10.0), messageNumber++);

        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

    // Provides an event handler for the ReceiveCompleted event.
    private static void MyReceiveCompleted(Object source,
        ReceiveCompletedEventArgs asyncResult)
    {
        // Connect to the queue.
        MessageQueue queue = (MessageQueue)source;

        // End the asynchronous receive operation.
        Message msg = queue.EndReceive(asyncResult.AsyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message number: {0}",
            (int)asyncResult.AsyncResult.AsyncState);
        Console.WriteLine("Message body: {0}", (string)msg.Body);
    }
}

Commenti

Nell'elaborazione asincrona si usa BeginReceive per generare l'evento ReceiveCompleted quando un messaggio diventa disponibile nella coda o quando è scaduto l'intervallo di tempo specificato.

ReceiveCompleted viene generato anche se nella coda esiste già un messaggio.

Utilizzare questo overload per associare le informazioni all'operazione che verrà mantenuta per tutta la durata dell'operazione. Il gestore eventi può rilevare queste informazioni esaminando la AsyncState proprietà dell'oggetto IAsyncResult associato all'operazione.

Per usare BeginReceive, creare un gestore eventi che elabora i risultati dell'operazione asincrona e associarlo al delegato dell'evento. BeginReceive avvia un'operazione di ricezione asincrona; l'oggetto MessageQueue riceve una notifica, tramite la generazione dell'evento ReceiveCompleted , quando un messaggio arriva nella coda. Può MessageQueue quindi accedere al messaggio chiamando EndReceive(IAsyncResult) o recuperando il risultato usando .ReceiveCompletedEventArgs

Il BeginReceive metodo restituisce immediatamente, ma l'operazione asincrona non viene completata fino a quando non viene chiamato il gestore eventi.

Poiché BeginReceive è asincrono, è possibile chiamarlo per ricevere un messaggio dalla coda senza bloccare il thread corrente di esecuzione. Per ricevere in modo sincrono un messaggio, usare il Receive metodo .

Al termine di un'operazione asincrona, è possibile chiamare BeginPeek o BeginReceive di nuovo nel gestore eventi per mantenere la ricezione delle notifiche.

Oggetto IAsyncResult che BeginReceive restituisce identifica l'operazione asincrona avviata dal metodo. È possibile usarlo IAsyncResult per tutta la durata dell'operazione, anche se in genere non viene usato fino a EndReceive(IAsyncResult) quando non viene chiamato. Tuttavia, se si avviano diverse operazioni asincrone, è possibile posizionarne IAsyncResult i valori in una matrice e specificare se attendere il completamento di tutte le operazioni o qualsiasi operazione. In questo caso, si usa la AsyncWaitHandle proprietà di IAsyncResult per identificare l'operazione completata.

Questo overload specifica un timeout e un oggetto di stato. Se l'intervallo specificato dal timeout parametro scade, questo componente genera l'evento ReceiveCompleted . Poiché non esiste alcun messaggio, una chiamata successiva a EndReceive(IAsyncResult) genererà un'eccezione.

L'oggetto stato associa le informazioni sullo stato all'operazione. Ad esempio, se si chiama BeginReceive più volte per avviare più operazioni, è possibile identificare ogni operazione tramite un oggetto di stato separato definito dall'utente.

È anche possibile usare l'oggetto stato per passare informazioni tra thread di processo. Se un thread viene avviato ma il callback si trova in un thread diverso in uno scenario asincrono, l'oggetto di stato viene sottoposto a marshalling e passato insieme alle informazioni dell'evento.

Non usare la chiamata BeginReceive asincrona con le transazioni. Se si vuole eseguire un'operazione asincrona transazionale, chiamare BeginPeeke inserire la transazione e il metodo (sincrono) Receive all'interno del gestore eventi creato per l'operazione di visualizzazione. Il gestore eventi potrebbe contenere funzionalità come illustrato nel codice C# seguente.

myMessageQueue.BeginTransaction();
 myMessageQueue.Receive();
 myMessageQueue.CommitTransaction();

Nella tabella seguente viene illustrato se questo metodo è disponibile in varie modalità gruppo di lavoro.

Modalità gruppo di lavoro Disponibile
Computer locale
Computer locale e nome del formato diretto
Computer remoto No
Nome del formato diretto e del computer remoto

Vedi anche

Si applica a

BeginReceive(TimeSpan, Object, AsyncCallback)

Avvia un'operazione di ricezione asincrona per la quale sono stati specificati un timeout e un oggetto di stato, che fornisce le informazioni associate per tutta la durata dell'operazione. Questo overload riceve mediante un callback la notifica dell'identità del gestore eventi per l'operazione. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda o non si verifica il timeout.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout, System::Object ^ stateObject, AsyncCallback ^ callback);
public IAsyncResult BeginReceive (TimeSpan timeout, object stateObject, AsyncCallback callback);
member this.BeginReceive : TimeSpan * obj * AsyncCallback -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan, stateObject As Object, callback As AsyncCallback) As IAsyncResult

Parametri

timeout
TimeSpan

Oggetto TimeSpan che indica il tempo di attesa necessario affinché un messaggio diventi disponibile.

stateObject
Object

Oggetto di stato, specificato dall'applicazione, che contiene le informazioni associate all'operazione asincrona.

callback
AsyncCallback

AsyncCallback che riceverà la notifica del completamento dell'operazione asincrona.

Restituisce

IAsyncResult che identifica la richiesta asincrona inviata.

Eccezioni

Il valore specificato per il parametro timeout non è valido.

Si è verificato un errore durante l'accesso a un metodo di Accodamento messaggi.

Esempio

Nell'esempio di codice seguente viene creata un'operazione di ricezione asincrona. Nell'esempio di codice viene inviato un messaggio a una coda di messaggi locale BeginReceive(TimeSpan, Object, AsyncCallback), quindi viene chiamato il passaggio: un valore di timeout di dieci secondi, un numero intero univoco che identifica il messaggio specifico e una nuova AsyncCallback istanza di che identifica il gestore eventiMyReceiveCompleted. Quando viene generato un ReceiveCompleted evento, il gestore eventi riceve il messaggio e scrive il corpo del messaggio e l'identificatore di messaggio intero nella schermata.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if (!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();       
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the ReceiveCompleted event.
void HandleReceiveCompleted(IAsyncResult^ asyncResult)
{
    // Connect to the queue.
    MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue");

    // End the asynchronous receive operation.
    Message^ msg = queue->EndReceive(asyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message number: {0}", asyncResult->AsyncState);
    Console::WriteLine("Message body: {0}", msg->Body);

    queue->Close();
}

int main()
{
    // Represents a state object associated with each message.
    int messageNumber = 0;

    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    MessageQueue^ queue = nullptr;
    try
    {
        CreateQueue(".\\exampleQueue", false);

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

        // Send a message to the queue.
        queue->Send("Example Message");

        // Begin the asynchronous receive operation.
        queue->BeginReceive(TimeSpan::FromSeconds(10.0), messageNumber++,
            gcnew AsyncCallback(HandleReceiveCompleted));

        // Simulate doing other work on the current thread.
        System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));
    }
    catch (InvalidOperationException^)
    {
        Console::WriteLine("Please install Message Queuing.");
    }

    catch (MessageQueueException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    finally
    {   
        queue->Close();
    }
}

using System;
using System.Messaging;

public class QueueExample
{
    // Represents a state object associated with each message.
    static int messageNumber = 0;

    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

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

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous receive operation.
        queue.BeginReceive(TimeSpan.FromSeconds(10.0), messageNumber++,
            new AsyncCallback(MyReceiveCompleted));
            
        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

    // Provides an event handler for the ReceiveCompleted event.
    private static void MyReceiveCompleted(IAsyncResult asyncResult)
    {
        // Connect to the queue.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // End the asynchronous receive operation.
        Message msg = queue.EndReceive(asyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message number: {0}", (int)asyncResult.AsyncState);
        Console.WriteLine("Message body: {0}", (string)msg.Body);
    }
}

Commenti

Quando si utilizza questo overload, il callback specificato nel parametro di callback viene richiamato direttamente quando un messaggio diventa disponibile nella coda o quando l'intervallo di tempo specificato è scaduto; l'evento ReceiveCompleted non viene generato. Gli altri overload di BeginReceive si basano su questo componente per generare l'evento ReceiveCompleted .

ReceiveCompleted viene generato anche se nella coda esiste già un messaggio.

Per usare BeginReceive, creare un gestore eventi che elabora i risultati dell'operazione asincrona e associarlo al delegato dell'evento. BeginReceive avvia un'operazione di ricezione asincrona; l'oggetto MessageQueue riceve una notifica, tramite la generazione dell'evento ReceiveCompleted , quando un messaggio arriva nella coda. Può MessageQueue quindi accedere al messaggio chiamando EndReceive(IAsyncResult) o recuperando il risultato usando .ReceiveCompletedEventArgs

Il BeginReceive metodo restituisce immediatamente, ma l'operazione asincrona non viene completata fino a quando non viene chiamato il gestore eventi.

Poiché BeginReceive è asincrono, è possibile chiamarlo per ricevere un messaggio dalla coda senza bloccare il thread corrente di esecuzione. Per ricevere in modo sincrono un messaggio, usare il Receive metodo .

Al termine di un'operazione asincrona, è possibile chiamare BeginPeek o BeginReceive di nuovo nel gestore eventi per mantenere la ricezione delle notifiche.

Oggetto IAsyncResult che BeginReceive restituisce identifica l'operazione asincrona avviata dal metodo. È possibile usarlo IAsyncResult per tutta la durata dell'operazione, anche se in genere non viene usato fino a EndReceive(IAsyncResult) quando non viene chiamato. Tuttavia, se si avviano diverse operazioni asincrone, è possibile posizionarne IAsyncResult i valori in una matrice e specificare se attendere il completamento di tutte le operazioni o qualsiasi operazione. In questo caso, si usa la AsyncWaitHandle proprietà di IAsyncResult per identificare l'operazione completata.

L'oggetto stato associa le informazioni sullo stato all'operazione. Ad esempio, se si chiama BeginReceive più volte per avviare più operazioni, è possibile identificare ogni operazione tramite un oggetto di stato separato definito dall'utente.

È anche possibile usare l'oggetto stato per passare informazioni tra thread di processo. Se un thread viene avviato ma il callback si trova in un thread diverso in uno scenario asincrono, l'oggetto di stato viene sottoposto a marshalling e passato insieme alle informazioni dell'evento.

Non usare la chiamata BeginReceive asincrona con le transazioni. Se si vuole eseguire un'operazione asincrona transazionale, chiamare BeginPeeke inserire la transazione e il metodo (sincrono) Receive all'interno del gestore eventi creato per l'operazione di visualizzazione. Il gestore eventi potrebbe contenere funzionalità come illustrato nel codice C# seguente.

myMessageQueue.BeginTransaction();
 myMessageQueue.Receive();
 myMessageQueue.CommitTransaction();

Nella tabella seguente viene illustrato se questo metodo è disponibile in varie modalità gruppo di lavoro.

Modalità gruppo di lavoro Disponibile
Computer locale
Computer locale e nome del formato diretto
Computer remoto No
Nome del formato diretto e del computer remoto

Vedi anche

Si applica a

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

Avvia un'operazione di ricezione asincrona che presenta il timeout specificato e che utilizza il cursore specificato, l'azione di lettura specificata e l'oggetto di stato specificato. L'oggetto di stato fornisce informazioni associate per l'intera durata dell'operazione. Questo overload riceve mediante un callback la notifica dell'identità del gestore eventi per l'operazione. L'operazione non è completa fino a quando un messaggio non viene reso disponibile nella coda o non si verifica il timeout.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Object ^ state, AsyncCallback ^ callback);
public IAsyncResult BeginReceive (TimeSpan timeout, System.Messaging.Cursor cursor, object state, AsyncCallback callback);
member this.BeginReceive : TimeSpan * System.Messaging.Cursor * obj * AsyncCallback -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan, cursor As Cursor, state As Object, callback As AsyncCallback) As IAsyncResult

Parametri

timeout
TimeSpan

Oggetto TimeSpan che indica il tempo di attesa necessario affinché un messaggio diventi disponibile.

cursor
Cursor

Oggetto Cursor che occupa una posizione specifica nella coda messaggi.

state
Object

Oggetto di stato, specificato dall'applicazione, che contiene le informazioni associate all'operazione asincrona.

callback
AsyncCallback

AsyncCallback che riceve la notifica del completamento dell'operazione asincrona.

Restituisce

IAsyncResult che identifica la richiesta asincrona inviata.

Eccezioni

Il valore del parametro cursor è null.

Il valore specificato per il parametro timeout non è valido.

Si è verificato un errore durante l'accesso a un metodo di Accodamento messaggi.

Commenti

Quando si utilizza questo overload, il callback specificato nel parametro di callback viene richiamato direttamente quando un messaggio diventa disponibile nella coda o quando l'intervallo di tempo specificato è scaduto; l'evento ReceiveCompleted non viene generato. Gli altri overload di BeginReceive si basano su questo componente per generare l'evento ReceiveCompleted .

ReceiveCompleted viene generato anche se nella coda esiste già un messaggio.

Per usare BeginReceive, creare un gestore eventi che elabora i risultati dell'operazione asincrona e associarlo al delegato dell'evento. BeginReceive avvia un'operazione di ricezione asincrona; l'oggetto MessageQueue riceve una notifica, tramite la generazione dell'evento ReceiveCompleted , quando un messaggio arriva nella coda. Può MessageQueue quindi accedere al messaggio chiamando EndReceive(IAsyncResult) o recuperando il risultato usando .ReceiveCompletedEventArgs

Il BeginReceive metodo restituisce immediatamente, ma l'operazione asincrona non viene completata fino a quando non viene chiamato il gestore eventi.

Poiché BeginReceive è asincrono, è possibile chiamarlo per ricevere un messaggio dalla coda senza bloccare il thread corrente di esecuzione. Per ricevere in modo sincrono un messaggio, usare il Receive metodo .

Al termine di un'operazione asincrona, è possibile chiamare BeginPeek o BeginReceive di nuovo nel gestore eventi per mantenere la ricezione delle notifiche.

Oggetto IAsyncResult che BeginReceive restituisce identifica l'operazione asincrona avviata dal metodo. È possibile usarlo IAsyncResult per tutta la durata dell'operazione, anche se in genere non viene usato fino a EndReceive(IAsyncResult) quando non viene chiamato. Tuttavia, se si avviano diverse operazioni asincrone, è possibile posizionarne IAsyncResult i valori in una matrice e specificare se attendere il completamento di tutte le operazioni o qualsiasi operazione. In questo caso, utilizzare la AsyncWaitHandle proprietà di IAsyncResult per identificare l'operazione completata.

L'oggetto stato associa le informazioni sullo stato all'operazione. Ad esempio, se si chiama BeginReceive più volte per avviare più operazioni, è possibile identificare ogni operazione tramite un oggetto di stato separato definito dall'utente.

È anche possibile usare l'oggetto stato per passare informazioni tra thread di processo. Se un thread viene avviato ma il callback si trova in un thread diverso in uno scenario asincrono, l'oggetto di stato viene sottoposto a marshalling e passato insieme alle informazioni dell'evento.

Non usare la chiamata BeginReceive asincrona con le transazioni. Se si vuole eseguire un'operazione asincrona transazionale, chiamare BeginPeeke inserire la transazione e il metodo (sincrono) Receive all'interno del gestore eventi creato per l'operazione di visualizzazione. Il gestore eventi potrebbe contenere funzionalità come illustrato nel codice C# seguente.

myMessageQueue.BeginTransaction();
 myMessageQueue.Receive();
 myMessageQueue.CommitTransaction();

Nella tabella seguente viene illustrato se questo metodo è disponibile in varie modalità gruppo di lavoro.

Modalità gruppo di lavoro Disponibile
Computer locale
Computer locale e nome del formato diretto
Computer remoto No
Nome del formato diretto e del computer remoto

Vedi anche

Si applica a

Thread safety

Il metodo non è thread-safe.