c# - 是否可以超时调用 HttpListener.GetContext?

标签 c# httplistener

根据HttpListener reference ,对 HttpListener.GetContext 的调用将阻塞,直到它从客户端收到 HTTP 请求。

我想知道我是否可以指定一个超时,以便在超时后函数返回。我觉得不然就不合理了,既然你不能保证会有一个请求让这个函数返回,那怎么能终止这个调用呢?

附言我知道它有一个异步版本 (BeginGetContext) 但问题仍然存在,因为 the corresponding EndGetContext will block until an HTTP request arrives .

因此,总会有一个线程(如果您使用多线程)无法返回,因为它在等待请求时被阻塞。

我错过了什么吗?

更新:

我找到了 this link有用。我还发现调用 HttpListener.Close() 实际上会终止由 BeginGetContext() 创建的等待线程。 HttpListener.Close() 以某种方式触发了 BeginGetContext() 注册的回调。因此,在执行 HttpListener.EndGetContext() 之前,请检查 HttpListener 是否已停止。

最佳答案

此外,如果您想在等待有限时间的进程处理中逐行执行,则 BeginGetContext 会返回一个 System.IAsyncResult 并公开 AsyncWaitHandle 属性

var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
context.AsyncWaitHandle.WaitOne();

Above 会阻塞线程,直到监听器接收到由分配给监听器的 heders 定义的有效内容,或者由于某些异常终止监听器线程并将结果返回给 ListenerCallback。

但是 AsyncWaitHandle.WaitOne() 可以带超时参数

// 5 seconds timeout
bool success = context.AsyncWaitHandle.WaitOne(5000, true);

if (success == false)
{
    throw new Exception("Timeout waiting for http request.");
}

ListenerCallback 可以包含对 listener.EndGetContext 的调用,或者如果 AsyncWaitHandle 没有指示超时或错误则直接调用 listener.EndGetContext

public static void ListenerCallback(IAsyncResult result)
{
    HttpListener listener = (HttpListener) result.AsyncState;
    // Use EndGetContext to complete the asynchronous operation.
    HttpListenerContext context = listener.EndGetContext(result);
    HttpListenerRequest request = context.Request;
    // Get response object.
    HttpListenerResponse response = context.Response;
    // Construct a response. 
    string responseString = "<HTML><BODY> It Works!</BODY></HTML>";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Write to response stream.
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    output.Write(buffer,0,buffer.Length);
    // Close the output stream.
    output.Close();
}

不要忘记使用 listener.BeginGetContext 告诉监听器再次监听

关于c# - 是否可以超时调用 HttpListener.GetContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9188352/

相关文章:

c# - 如何在 C# 中读写二进制文件?

c# - DI 与一次性元素

c# - TcpClient 未正确接收数据

不使用 netsh 注册 URI 的 C# HttpListener

java - 从 Glassfish 2.1 迁移到 Glassfish 4.1 后无法发送电子邮件

c# - HttpListener 在 Mono 上运行良好吗?

c# - 使用三元运算符而不是 IF THEN 有什么意义?

c# - 在 MonoDevelop 和 GTKSharp 中使用小部件

c# - 在 httplisteners authenticationselectordelegate 中提供身份验证被拒绝的消息

c# - 带有发布数据的 httplistener