HttpListener.BeginGetContext(AsyncCallback, Object) Método

Definição

Começa a recuperação assíncrona de uma solicitação de entrada.

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

Parâmetros

callback
AsyncCallback

Um delegado AsyncCallback que faz referência ao método a ser invocado quando uma solicitação do cliente está disponível.

state
Object

Um objeto definido pelo usuário que contém informações sobre a operação. Esse objeto é passado para o representante callback quando a operação é concluída.

Retornos

Um objeto IAsyncResult que indica o status da operação assíncrona.

Exceções

Falha em uma chamada de função do Win32. Verifique a propriedade ErrorCode da exceção para determinar a causa da exceção.

Esse objeto não foi iniciado ou está parado no momento.

Este objeto está fechado.

Exemplos

O exemplo de código a seguir demonstra como usar o BeginGetContext método para especificar um método de retorno de chamada que tratará as solicitações de entrada do cliente.


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

O exemplo de código a seguir implementa um método de retorno de chamada.

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

Comentários

O BeginGetContext método inicia uma chamada assíncrona (sem bloqueio) para receber solicitações de cliente de entrada. Antes de chamar esse método, você deve chamar o Start método e adicionar pelo menos um prefixo de URI (Uniform Resource Identifier) para escutar adicionando as cadeias de caracteres de URI ao HttpListenerPrefixCollection retornado pela Prefixes propriedade .

A operação assíncrona deve ser concluída chamando o EndGetContext método . Normalmente, o método é invocado pelo callback delegado.

Esse método não bloqueia enquanto a operação é concluída. Para obter uma solicitação de entrada e bloquear até que a operação seja concluída, chame o GetContext método .

Para obter informações detalhadas sobre como usar o modelo de programação assíncrona, consulte Chamando métodos síncronos de forma assíncrona.

Notas aos Chamadores

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo. Para obter mais informações, consulte Rastreamento de rede no .NET Framework.

Aplica-se a