HttpListener.BeginGetContext(AsyncCallback, Object) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Começa a recuperar de forma assíncrona um pedido recebido.
public:
IAsyncResult ^ BeginGetContext(AsyncCallback ^ callback, System::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 AsyncCallback delegado que referencia o método a invocar quando um pedido de cliente está disponível.
- state
- Object
Um objeto definido pelo utilizador que contém informação sobre a operação. Este objeto é passado para o callback delegado quando a operação termina.
Devoluções
Um IAsyncResult objeto que indica o estado da operação assíncrona.
Exceções
Uma chamada de função Win32 falhou. Verifique a propriedade da ErrorCode exceção para determinar a causa da dela.
Este objeto ainda não foi ligado nem está atualmente parado.
Este objeto está fechado.
Exemplos
O exemplo de código seguinte demonstra o uso do BeginGetContext método para especificar um método de callback que irá lidar com pedidos de clientes recebidos.
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 seguinte implementa um método de callback.
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
Observações
O BeginGetContext método inicia uma chamada assíncrona (não bloqueante) para receber pedidos de clientes recebidos. Antes de chamar este método, deve chamar o Start método e adicionar pelo menos um prefixo de Identificador Uniforme de Recursos (URI) para ouvir, adicionando as cadeias de URI ao HttpListenerPrefixCollection devolvido 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.
Este método não bloqueia enquanto a operação está concluída. Para receber um pedido recebido e bloquear até a operação terminar, chame o GetContext método.
Para informações detalhadas sobre a utilização do modelo de programação assíncrona, veja Chamar Métodos Síncronos Assíncronos.
Notas para Chamadores
Esse membro gera informações de rastreamento quando você habilita o rastreamento de rede em seu aplicativo. Para mais informações, consulte Rastreamento de Rede no .NET Framework.