Share via


使用 AsyncWaitHandle 封鎖應用程式執行

無法在等候非同步作業 (Asynchronous Operation) 結果時,繼續進行其他工作的應用程式,必須在作業完成之前維持封鎖。 請使用下列其中一個選項,在等候非同步作業完成時,封鎖您應用程式的主執行緒:

在非同步作業完成之前,使用一或多個 WaitHandle 物件來封鎖的應用程式,通常都會呼叫 BeginOperationName 方法,來執行不需要作業結果即可完成的工作,然後在非同步作業完成之前維持封鎖。 只要使用 AsyncWaitHandle 呼叫其中一個 WaitOne 方法,應用程式即可封鎖單一作業。 若要在等候一組非同步作業完成的同時封鎖,請將關聯的 AsyncWaitHandle 物件儲存到陣列中,並呼叫其中一個 WaitAll 方法。 若要在等候任何一組非同步作業完成的同時封鎖,請將關聯的 AsyncWaitHandle 物件儲存到陣例中,並呼叫其中一個 WaitAny 方法。

範例

下列程式碼範例會示範在 DNS 類別中使用非同步方法,以擷取使用者所指定之電腦的網域名稱系統資訊。 且會示範使用與非同步作業關聯的 WaitHandle 來進行封鎖。 請注意,由於在使用此處理方法時不需要 BeginGetHostByName requestCallback 和 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);
            }
        }
    }
}

請參閱

概念

事件架構非同步模式概觀

其他資源

非同步程式設計模式