HttpListener.BeginGetContext(AsyncCallback, Object) 메서드

정의

들어오는 요청에 대한 비동기 검색을 시작합니다.

public:
 IAsyncResult ^ BeginGetContext(AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginGetContext (AsyncCallback? callback, object? state);
public IAsyncResult BeginGetContext (AsyncCallback callback, object state);
member this.BeginGetContext : AsyncCallback * obj -> IAsyncResult
Public Function BeginGetContext (callback As AsyncCallback, state As Object) As IAsyncResult

매개 변수

callback
AsyncCallback

클라이언트 요청을 사용할 수 있을 때 호출할 메서드를 참조하는 AsyncCallback 대리자입니다.

state
Object

작업에 대한 정보가 들어 있는 사용자 정의 개체입니다. 작업이 완료되면 callback 대리자에게 전달되는 개체입니다.

반환

비동기 작업의 상태를 나타내는 IAsyncResult 개체입니다.

예외

Win32 함수 호출이 실패한 경우. 예외의 ErrorCode 속성을 검토하여 예외의 원인을 확인할 수 있습니다.

이 개체가 시작되지 않았거나 현재 중지된 경우

이 개체가 닫혀 있는 경우

예제

다음 코드 예제에서는 메서드를 BeginGetContext 사용하여 들어오는 클라이언트 요청을 처리할 콜백 메서드를 지정하는 방법을 보여 줍니다.


public static void NonblockingListener(string [] prefixes)
{
    HttpListener listener = new HttpListener();
    foreach (string s in prefixes)
    {
        listener.Prefixes.Add(s);
    }
    listener.Start();
    IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback),listener);
    // Applications can do some work here while waiting for the
    // request. If no work can be done until you have processed a request,
    // use a wait handle to prevent this thread from terminating
    // while the asynchronous operation completes.
    Console.WriteLine("Waiting for request to be processed asyncronously.");
    result.AsyncWaitHandle.WaitOne();
    Console.WriteLine("Request processed asyncronously.");
    listener.Close();
}
Public Shared Sub NonblockingListener(ByVal prefixes As String())
    Dim listener As HttpListener = New HttpListener()

    For Each s As String In prefixes
        listener.Prefixes.Add(s)
    Next

    listener.Start()
    Dim result As IAsyncResult = listener.BeginGetContext(New AsyncCallback(AddressOf ListenerCallback), listener)
    ' Applications can do some work here while waiting for the 
    ' request. If no work can be done until you have processed a request,
    ' use a wait handle to prevent this thread from terminating
    ' while the asynchronous operation completes.
    Console.WriteLine("Waiting for request to be processed asyncronously.")
    result.AsyncWaitHandle.WaitOne()
    Console.WriteLine("Request processed asyncronously.")
    listener.Close()
End Sub

다음 코드 예제에서는 콜백 메서드를 구현합니다.

public static void ListenerCallback(IAsyncResult result)
{
    HttpListener listener = (HttpListener) result.AsyncState;
    // Call EndGetContext to complete the asynchronous operation.
    HttpListenerContext context = listener.EndGetContext(result);
    HttpListenerRequest request = context.Request;
    // Obtain a response object.
    HttpListenerResponse response = context.Response;
    // Construct a response.
    string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    output.Write(buffer,0,buffer.Length);
    // You must close the output stream.
    output.Close();
}
Public Shared Sub ListenerCallback(ByVal result As IAsyncResult)
    Dim listener As HttpListener = CType(result.AsyncState, HttpListener)
    ' Call EndGetContext to complete the asynchronous operation.
    Dim context As HttpListenerContext = listener.EndGetContext(result)
    Dim request As HttpListenerRequest = context.Request
    ' Obtain a response object.
    Dim response As HttpListenerResponse = context.Response
    ' Construct a response.
    Dim responseString As String = "<HTML><BODY> Hello world!</BODY></HTML>"
    Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(responseString)
    ' Get a response stream and write the response to it.
    response.ContentLength64 = buffer.Length
    Dim output As System.IO.Stream = response.OutputStream
    output.Write(buffer, 0, buffer.Length)
    ' You must close the output stream.
    output.Close()
End Sub

설명

메서드는 BeginGetContext 들어오는 클라이언트 요청을 수신하기 위해 비동기(비차단) 호출을 시작합니다. 이 메서드를 호출하기 전에 메서드를 Start 호출하고 속성에서 반환 Prefixes 된 에 URI 문자열 HttpListenerPrefixCollection 을 추가하여 수신 대기할 하나 이상의 URI(Uniform Resource Identifier) 접두사를 추가해야 합니다.

메서드를 호출 EndGetContext 하여 비동기 작업을 완료해야 합니다. 일반적으로 메서드는 대리자에서 호출됩니다 callback .

이 메서드는 작업이 완료되는 동안 차단되지 않습니다. 들어오는 요청을 가져와 작업이 완료될 때까지 차단하려면 메서드를 GetContext 호출합니다.

비동기 프로그래밍 모델 사용에 대한 자세한 내용은 동기 메서드 비동기 호출을 참조하세요.

호출자 참고

애플리케이션에 네트워크 추적을 사용하도록 설정하면 이 멤버에서 추적 정보를 출력합니다. 자세한 내용은 .NET Framework 네트워크 추적을 참조하세요.

적용 대상