使用 AsyncWaitHandle 阻止应用程序的执行

如果应用无法在等待异步操作结果期间继续执行其他工作,必须阻止应用一直到操作完成。 请使用下列方法之一,在应用等待异步操作完成期间阻止应用的主线程:

在异步操作完成前使用一个或多个 WaitHandle 对象阻止的应用,通常会调用 BeginOperationName 方法,执行任何不需要等待操作结果也可以执行的工作,并在一个或多个异步操作完成前一直处于阻止状态。 可以使用 AsyncWaitHandle 调用 WaitOne 方法之一,对单个操作阻止应用。 若要在等待一组异步操作完成期间阻止应用,请将关联的 AsyncWaitHandle 对象存储到数组中,并调用 WaitAll 方法之一。 若要在等待一组异步操作中任一操作完成期间阻止应用,请将关联的 AsyncWaitHandle 对象存储到数组中,并调用 WaitAny 方法之一。

示例

下面的代码示例展示了如何使用 DNS 类中的异步方法,检索用户指定计算机的域名系统信息。 此示例展示了如何使用与异步操作关联的 WaitHandle 阻止应用。 请注意,对 BeginGetHostByNamerequestCallbackstateObject 参数传递的是 null(Visual Basic 中的 Nothing),因为使用这种方法时这些是可选参数。

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

另请参阅