다음을 통해 공유


AsyncWaitHandle을 사용하여 애플리케이션 실행 차단

비동기 작업의 결과를 기다리는 동안 다른 작업을 계속할 수 없는 애플리케이션은 작업이 완료될 때까지 차단해야 합니다. 비동기 작업이 완료 될 때까지 기다리는 동안 애플리케이션의 주 스레드를 차단 하려면 다음 옵션 중 하나를 사용 합니다.

비동기 작업이 완료될 때까지 하나 이상의 WaitHandle 개체를 사용하여 차단하는 애플리케이션은 일반적으로 BeginOperationName 메서드를 호출하고, 작업 결과 없이 수행할 수 있는 모든 작업을 수행한 다음, 비동기 작업이 완료될 때까지 차단합니다. 애플리케이션이 WaitOne 메서드를 사용하여 AsyncWaitHandle 중 하나를 호출하여 단일 작업을 차단할 수 있습니다. 비동기 작업 집합이 완료될 때까지 기다리는 동안 차단하려면 연결된 AsyncWaitHandle 개체를 배열에 저장하고 메서드 중 WaitAll 하나를 호출합니다. 비동기 작업 집합 중 하나가 완료될 때까지 기다리는 동안 차단하려면 연결된 AsyncWaitHandle 개체를 배열에 저장하고 메서드 중 WaitAny 하나를 호출합니다.

예시

다음 코드 예제에서는 DNS 클래스에서 비동기 메서드를 사용 하 여 사용자 지정 된 컴퓨터에 대 한 도메인 이름 시스템 정보를 검색 하는 방법을 보여 줍니다. 이 예제는 비동기 작업과 관련된 WaitHandle을(를) 사용하여 차단하는 방법을 보여줍니다. nullNothing(Visual Basic의 경우)는 이 방법을 사용할 때 필요하지 않으므로, BeginGetHostByNamerequestCallbackstateObject 매개 변수에 전달됩니다.

/*
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($"{aliases[i]}");
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses");
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine($"{addresses[i].ToString()}");
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine($"Exception occurred while processing the request: {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

참고하십시오