HttpListener.EndGetContext(IAsyncResult) 方法

定義

完成擷取傳入用戶端要求的非同步作業。

public:
 System::Net::HttpListenerContext ^ EndGetContext(IAsyncResult ^ asyncResult);
public System.Net.HttpListenerContext EndGetContext (IAsyncResult asyncResult);
member this.EndGetContext : IAsyncResult -> System.Net.HttpListenerContext
Public Function EndGetContext (asyncResult As IAsyncResult) As HttpListenerContext

參數

asyncResult
IAsyncResult

啟動非同步作業時所取得的 IAsyncResult 物件。

傳回

HttpListenerContext 物件,代表用戶端要求。

例外狀況

未呼叫 BeginGetContext(AsyncCallback, Object) 方法,取得 asyncResult

asyncResultnull

Win32 函式呼叫失敗。 請檢查例外狀況的 ErrorCode 屬性,以判斷造成例外狀況的原因。

已針對指定的 asyncResult 物件,呼叫 EndGetContext(IAsyncResult) 方法。

這個物件已經關閉。

範例

下列程式代碼範例示範呼叫 方法的回呼方法實作 EndGetContext

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

備註

呼叫 EndGetContext 方法通常是在委派叫用的應用程式定義回呼方法內,以取得 HttpListenerContext 包含傳入用戶端要求及其相關響應的物件。 這個方法會完成先前藉由呼叫 方法啟動的 BeginGetContext 作業。 如果作業尚未完成,這個方法會封鎖,直到完成為止。

因為呼叫 EndGetContext 方法需要 HttpListener 物件,所以這個物件通常會使用傳遞至 方法的狀態對象傳遞至 BeginGetContext 回呼方法。 您可以使用 物件的 屬性asyncResult來取得這個狀態物件AsyncState

如需使用異步程序設計模型的詳細資訊,請參閱 以異步方式呼叫同步方法

給呼叫者的注意事項

在應用程式中啟用網路追蹤時,這個成員會輸出追蹤資訊。 如需詳細資訊,請參閱 .NET Framework 中的網路追蹤

適用於