使用 AsyncWaitHandle 封鎖應用程式執行Blocking Application Execution Using an AsyncWaitHandle

等待非同步作業的結果而無法繼續執行其他工作的應用程式必須封鎖,直到作業完成為止。Applications that cannot continue to do other work while waiting for the results of an asynchronous operation must block until the operation completes. 使用下列其中一個選項,在等候非同步作業完成時封鎖應用程式的主執行緒:Use one of the following options to block your application's main thread while waiting for an asynchronous operation to complete:

在非同步作業完成之前,使用一個或多個 WaitHandle 物件封鎖的應用程式通常會呼叫 BeginOperationName 方法,執行不需作業結果即可完成的任何工作,然後在非同步作業完成之前維持封鎖。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. 使用 AsyncWaitHandle 來呼叫其中一個 WaitOne 方法,可在單一作業上封鎖應用程式。An application can block on a single operation by calling one of the WaitOne methods using the AsyncWaitHandle. 若要在等待一組非同步作業完成時封鎖,請將相關的 AsyncWaitHandle 物件儲存在陣列,並呼叫其中一個 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. 若要在等待一組非同步作業的任何一個作業完成時封鎖,請將相關的 AsyncWaitHandle 物件儲存在陣列,並呼叫其中一個 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.

範例Example

下列範例示範在 DNS 類別中使用非同步方法,以擷取使用者指定電腦的網域名稱系統資訊。The following code example demonstrates using asynchronous methods in the DNS class to retrieve Domain Name System information for a user-specified computer. 此範例示範使用與非同步作業相關聯的 WaitHandle 進行封鎖。The example demonstrates blocking using the WaitHandle associated with the asynchronous operation. 請注意,因為使用此方式時並不需要 BeginGetHostByNamerequestCallbackstateObject 參數,所以已為其傳遞 null (在 Visual Basic 中為 Nothing)。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

另請參閱See also