gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:51:02 43 4
gpt4 key购买 nike

根据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/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com