다음을 통해 공유


비동기 작업의 상태에 대한 폴링

비동기 작업 결과를 기다리는 동안 다른 작업을 수행할 수 있는 응용 프로그램은 해당 작업이 완료될 때까지 기다리는 동안 블로킹되지 않아야 합니다. 다음 옵션 중 하나를 사용하여 비동기 작업이 완료될 때까지 기다리는 동안 명령을 계속 실행합니다.

  • 비동기 작업의 BeginOperationName 메서드에서 반환한 IAsyncResultIsCompleted 속성을 사용하여 해당 작업이 완료되었는지 여부를 확인합니다. 폴링이라고 하는 방법에 대해서는 이 항목에서 설명합니다.

  • AsyncCallback 대리자를 사용하여 비동기 작업 결과를 별도의 스레드에서 처리합니다. 이 방법을 보여 주는 예제를 보려면 AsyncCallback 대리자를 사용하여 비동기 작업 종료를 참조하십시오.

예제

다음 코드 예제에서는 Dns 클래스의 비동기 메서드를 사용하여 사용자 지정 컴퓨터의 Domain Name System 정보를 검색하는 방법을 보여 줍니다. 이 예제에서는 비동기 작업을 시작한 다음 작업이 완료 때까지 콘솔에 마침표(".")를 인쇄합니다. 이 방법을 사용할 때 BeginGetHostByName AsyncCallbackObject 매개 변수가 필요하지 않으므로 이 인수에 null(Visual Basic의 경우 Nothing)이 전달됩니다.


'The following example demonstrates using asynchronous methods to
'get Domain Name System information for the specified host computer.
'This example polls to detect the end of the asynchronous operation.

Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading

Namespace Examples.AdvancedProgramming.AsynchronousOperations

    Public Class PollUntilOperationCompletes
        Shared Sub UpdateUserInterface()
            ' Print a period to indicate that the application
            ' is still working on the request.
            Console.Write(".")
        End Sub
        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...")

            ' Poll for completion information.
            ' Print periods (".") until the operation completes.
            Do while result.IsCompleted <> True
                UpdateUserInterface()
            Loop
            ' The operation is complete. Process the results.
            ' Print a new line.
            Console.WriteLine()
            Try 
                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.
This example polls to detect the end of the asynchronous operation.
*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Examples.AdvancedProgramming.AsynchronousOperations
{
    public class PollUntilOperationCompletes
    {
        static void UpdateUserInterface()
        {
            // Print a period to indicate that the application
            // is still working on the request.
            Console.Write(".");
        }
        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 asychronous request for DNS information.
            IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);
            Console.WriteLine("Processing request for information...");

            // Poll for completion information.
            // Print periods (".") until the operation completes.
            while (result.IsCompleted != true)
            {
                UpdateUserInterface();
            }
            // The operation is complete. Process the results.
            // Print a new line.
            Console.WriteLine();
            try 
            {
                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("An exception occurred while processing the request: {0}", e.Message);
            }
        }
    }
}

참고 항목

개념

이벤트 기반 비동기 패턴 개요

기타 리소스

비동기 프로그래밍 디자인 패턴