我试图包装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();
}
}但是当我调用外部函数(包装类的外部函数)时,使用:
HttpListenerContext listenerContext = await listener.GetContextAsync();在实现第一个连接之前,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;
}发布于 2017-05-29 21:58:19
如果你仔细观察你的方法:
public Task<HttpListenerContext> GetContextAsync()
{
Task<HttpListenerContext> contextTask = listener.GetContextAsync();
if (contextTask.Result.Request.IsWebSocketRequest)您正在使contextTask阻塞线程,直到它通过使用结果获得一些响应为止:
访问属性的get访问器会阻塞调用线程,直到异步操作完成为止;这相当于调用等待方法。
基本上,你需要这样的东西:
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
}
}https://stackoverflow.com/questions/44250716
复制相似问题