Blocage de l'exécution d'applications à l'aide d'un AsyncWaitHandleBlocking Application Execution Using an AsyncWaitHandle

Les applications qui ne peuvent pas continuer à effectuer d’autres tâches en attendant les résultats d’une opération asynchrone doivent se bloquer jusqu'à ce que cette opération se termine.Applications that cannot continue to do other work while waiting for the results of an asynchronous operation must block until the operation completes. Pour bloquer le thread principal de votre application en attendant la fin d’une opération asynchrone, utilisez l’une des options suivantes :Use one of the following options to block your application's main thread while waiting for an asynchronous operation to complete:

Les applications qui utilisent un ou plusieurs objets WaitHandle pour se bloquer jusqu’à la fin d’une opération asynchrone appellent généralement la méthode BeginNomOpération, effectuent tout le travail réalisable sans les résultats de l’opération, puis se bloquent jusqu’à la fin de la ou des opérations asynchrones.Applications that use one or more WaitHandle objects to block until an asynchronous operation is complete will typically call the BeginOperationName method, perform any work that can be done without the results of the operation, and then block until the asynchronous operation(s) completes. Une application peut se bloquer sur une seule opération en appelant l’une des méthodes WaitOne à l’aide du AsyncWaitHandle.An application can block on a single operation by calling one of the WaitOne methods using the AsyncWaitHandle. Pour imposer un blocage en attendant qu’un ensemble d’opérations asynchrones se termine, stockez les objets AsyncWaitHandle associés dans un tableau et appelez l’une des méthodes WaitAll.To block while waiting for a set of asynchronous operations to complete, store the associated AsyncWaitHandle objects in an array and call one of the WaitAll methods. Pour imposer un blocage en attendant que l’une des opérations asynchrones se termine, stockez les objets AsyncWaitHandle associés dans un tableau et appelez l’une des méthodes WaitAny.To block while waiting for any one of a set of asynchronous operations to complete, store the associated AsyncWaitHandle objects in an array and call one of the WaitAny methods.

ExempleExample

L’exemple de code suivant montre comment utiliser des méthodes asynchrones dans la classe DNS afin de récupérer les informations DNS (Domain Name System) pour un ordinateur spécifié par l’utilisateur.The following code example demonstrates using asynchronous methods in the DNS class to retrieve Domain Name System information for a user-specified computer. Il illustre le blocage avec la WaitHandle associée à l’opération asynchrone.The example demonstrates blocking using the WaitHandle associated with the asynchronous operation. Notez que null (Nothing en Visual Basic) est transmis aux paramètres BeginGetHostByNamerequestCallback et stateObject, car ils ne sont pas requis dans cette approche.Note that null (Nothing in Visual Basic) is passed for the BeginGetHostByNamerequestCallback and stateObject parameters because these are not required when using this approach.

/*
The following example demonstrates using asynchronous methods to
get Domain Name System information for the specified host computer.

*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Examples.AdvancedProgramming.AsynchronousOperations
{
    public class WaitUntilOperationCompletes
    {
        public static void Main(string[] args)
        {
            // Make sure the caller supplied a host name.
            if (args.Length == 0 || args[0].Length == 0)
            {
                // Print a message and exit.
                Console.WriteLine("You must specify the name of a host computer.");
                return;
            }
            // Start the asynchronous request for DNS information.
            IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);
            Console.WriteLine("Processing request for information...");
            // Wait until the operation completes.
            result.AsyncWaitHandle.WaitOne();
            // The operation completed. Process the results.
            try 
            {
                // Get the results.
                IPHostEntry host = Dns.EndGetHostEntry(result);
                string[] aliases = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("Aliases");
                    for (int i = 0; i < aliases.Length; i++)
                    {
                        Console.WriteLine("{0}", aliases[i]);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses");
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine("{0}",addresses[i].ToString());
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Exception occurred while processing the request: {0}", 
                    e.Message);
            }
        }
    }
}
' The following example demonstrates using asynchronous methods to
' get Domain Name System information for the specified host computer.

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading

namespace Examples.AdvancedProgramming.AsynchronousOperations
    Public Class WaitUntilOperationCompletes
    
        Public Shared Sub Main(args() as String)
            ' Make sure the caller supplied a host name.
            If(args.Length = 0)
                ' Print a message and exit.
                Console.WriteLine("You must specify the name of a host computer.")
                End
            End If
            ' Start the asynchronous request for DNS information.
            Dim result as IAsyncResult= Dns.BeginGetHostEntry(args(0), Nothing, Nothing)
            Console.WriteLine("Processing request for information...")
            ' Wait until the operation completes.
            result.AsyncWaitHandle.WaitOne()
            ' The operation completed. Process the results.
            Try 
                ' Get the results.
                Dim host as IPHostEntry = Dns.EndGetHostEntry(result)
                Dim  aliases() as String = host.Aliases
                Dim addresses() as IPAddress= host.AddressList
                Dim i as Integer
                If aliases.Length > 0
                    Console.WriteLine("Aliases")
                    For i = 0 To aliases.Length -1 
                        Console.WriteLine("{0}", aliases(i))
                    Next i
                End If
                If addresses.Length > 0
                    Console.WriteLine("Addresses")
                    For i = 0 To addresses.Length -1
                        Console.WriteLine("{0}", addresses(i).ToString())
                    Next i
                End If
            Catch e as SocketException
                  Console.WriteLine("An exception occurred while processing the request: {0}" _
                    , e.Message)
            End Try
        End Sub
    End Class
End Namespace

Voir aussiSee also