包装`HttpListener`的`GetContextAsync()`

gal*_*h92 0 c# asynchronous task async-await

我正在尝试包装HttpListener该类并添加更多处理Web套接字的逻辑.

最后,我试图将GetContextAsync()方法包装为仅返回HttpListenerContext作为Web套接字的对象.

到目前为止,我有:

public Task<HttpListenerContext> GetContextAsync()
{
    Task<HttpListenerContext> contextTask = listener.GetContextAsync();
    if (contextTask.Result.Request.IsWebSocketRequest)
    {
        return contextTask;
    }
    else
    {
        contextTask.Result.Response.StatusCode = 500;
        contextTask.Result.Response.Close();
        return GetContextAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我调用外部函数(包装类)时,使用:

HttpListenerContext listenerContext = await listener.GetContextAsync();
Run Code Online (Sandbox Code Playgroud)

await实现第一次连接之前,不会返回主线程.


编辑

如果它对某人有帮助,我最终会采取以下措施:

public async Task<HttpListenerContext> GetContextAsync()
{
    HttpListenerContext listenerContext = await listener.GetContextAsync();
    while (!listenerContext.Request.IsWebSocketRequest)
    {
        listenerContext.Response.StatusCode = 500;
        listenerContext.Response.Close();
        listenerContext = await listener.GetContextAsync();
    }
    return listenerContext;
}
Run Code Online (Sandbox Code Playgroud)

SO *_*ood 7

如果你仔细看看你的方法:

public Task<HttpListenerContext> GetContextAsync()
{
    Task<HttpListenerContext> contextTask = listener.GetContextAsync();
    if (contextTask.Result.Request.IsWebSocketRequest)
Run Code Online (Sandbox Code Playgroud)

您正在使contextTask阻塞线程,直到它通过使用Result得到一些响应:

访问属性的get访问器会阻塞调用线程,直到异步操作完成; 它等同于调用Wait方法.

基本上,你需要这样的东西:

public async Task<HttpListenerContext> GetContextAsync()
{
    HttpListenerContext context = await listener.GetContextAsync();
    if (context.Request.IsWebSocketRequest)
    {
        return context;
    }
    else
    {
        context.Response.StatusCode = 500;
        context.Response.Close();
        return await GetContextAsync(); //not sure here
    }
}
Run Code Online (Sandbox Code Playgroud)