是否可以使用超时调用HttpListener.GetContext?

KFL*_*KFL 9 c# httplistener

根据HttpListener引用,对HttpListener.GetContext的调用将阻塞,直到它从客户端获取HTTP请求.

我想知道我是否可以指定超时,以便在超时后函数将返回.我认为否则这是不合理的,因为你无法保证会有一个请求让这个函数返回,那么如何终止这个调用呢?

PS我知道它有一个异步版本(BeginGetContext)但问题仍然存在,因为相应的EndGetContext将阻塞,直到HTTP请求到达.

因此,总会有一个线程(如果你这样做多线程)无法返回,因为它在等待请求时被阻止.

我错过了什么吗?

更新:

我发现这个链接很有用.我还发现调用HttpListener.Close()实际上终止了BeginGetContext()创建的等待线程.不知何故,HttpListener.Close()触发BeginGetContext()注册的回调.因此,在执行HttpListener.EndGetContext()之前,请检查HttpListener是否已停止.

tof*_*ofo 6

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

var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
context.AsyncWaitHandle.WaitOne();
Run Code Online (Sandbox Code Playgroud)

上面阻塞线程,直到侦听器收到由分配给侦听器的标题定义的有效内容,或者由于某些异常终止侦听器线程并将结果返回给ListenerCallback而终止.

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

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

if (success == false)
{
    throw new Exception("Timeout waiting for http request.");
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

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


Zen*_*xer 2

除非 HTTP 请求已到达,或者侦听器失败(在这种情况下 EndGetContext 将引发异常),否则不应调用调用 EndGetContext 的回调。因此,如果使用得当,它不会阻塞。

BeginGetContext 和 EndGetContext(即异步操作)正是您想要的。

Begin 和 End 方法的工作原理是,Begin 说“当 X 准备好时向我发出信号”,End 说“将您刚刚向我发出信号的 X 给我”。当然,后者理论上会阻塞,但会瞬间返回。