首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >包装``HttpListener`‘’`GetContextAsync()‘

包装``HttpListener`‘’`GetContextAsync()‘
EN

Stack Overflow用户
提问于 2017-05-29 21:52:44
回答 1查看 1.3K关注 0票数 0

我试图包装HttpListener类并添加更多处理Web的逻辑。

最后,我试图包装GetContextAsync()方法,只返回HttpListenerContext对象,这些对象是web套接字。

到目前为止,我已经:

代码语言:javascript
复制
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();
    }
}

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

代码语言:javascript
复制
HttpListenerContext listenerContext = await listener.GetContextAsync();

在实现第一个连接之前,await不会返回到主线程。

编辑

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

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-29 21:58:19

如果你仔细观察你的方法:

代码语言:javascript
复制
public Task<HttpListenerContext> GetContextAsync()
{
    Task<HttpListenerContext> contextTask = listener.GetContextAsync();
    if (contextTask.Result.Request.IsWebSocketRequest)

您正在使contextTask阻塞线程,直到它通过使用结果获得一些响应为止:

访问属性的get访问器会阻塞调用线程,直到异步操作完成为止;这相当于调用等待方法。

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

代码语言:javascript
复制
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
    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44250716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档