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

更新:2007 年 11 月

如果应用程序在等待异步操作结果时不能继续执行其他工作,则在操作完成之前,必须阻止执行其他工作。可以使用下列方法之一来在等待异步操作完成时阻止应用程序的主线程。

那些在异步操作完成前一直使用一个或多个 WaitHandle 对象进行阻止的应用程序通常会调用 Begin操作名称 方法,执行任何不需要等待操作结果也可以执行的工作,然后一直等到异步操作完成才停止阻止。通过使用 AsyncWaitHandle 调用 WaitOne 方法之一,应用程序可以阻止一个操作。若要在等待一组异步操作完成期间阻止执行,应将相关的 AsyncWaitHandle 对象存储在数组中,然后调用 WaitAll 方法之一。若要在等待一组异步操作中的任一操作完成时阻止其他操作,应将关联的 AsyncWaitHandle 对象存储在数组中,然后调用 WaitAny 方法之一。

示例

下面的代码示例演示如何使用 DNS 类中的异步方法来检索用户指定的计算机的域名系统信息。此示例演示如何使用与异步操作关联的 WaitHandle 来阻止。请注意,示例中为 BeginGetHostByNamerequestCallback 和 stateObject 参数传递了 null(在 Visual Basic 中为 Nothing),因为使用此方法时不需要这两个参数。

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

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

请参见

概念

基于事件的异步模式概述

其他资源

异步编程设计模式