我已經做到了是爲具有對HttpListener
偵聽使用阻斷GetContext()
方法,但只要它接收到一個請求,通過使用IAsyncResult
圖案做一個異步調用將其傳遞給另一個線程的螺紋的方式與這似乎工作正常。
private void Run()
{
while (true)
{
if (this._disposed || this._shouldTerminate) return;
if (this._listener.IsListening)
{
try
{
HttpListenerContext context = this._listener.GetContext();
//Hand it off to be processed asynchronously
this._delegate.BeginInvoke(context, new AsyncCallback(this.EndRequest), null);
}
catch (Exception ex)
{
this.LogErrors(ex);
}
}
}
}
private delegate HttpServerContext HandleRequestDelegate(HttpListenerContext context);
private HttpServerContext HandleRequest(HttpListenerContext context)
{
IHttpListenerHandler handler;
HttpServerContext serverContext = new HttpServerContext(this, context);
try
{
bool skipHandling = this.ApplyPreRequestModules(serverContext);
if (!skipHandling)
{
handler = this._handlers.GetHandler(serverContext);
handler.ProcessRequest(serverContext);
}
}
catch (NoHandlerException noHandlerEx)
{
this.LogErrors(noHandlerEx);
context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
}
catch (HttpServerException serverEx)
{
this.LogErrors(serverEx);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
return serverContext;
}
private void EndRequest(IAsyncResult result)
{
try
{
HttpServerContext context = this._delegate.EndInvoke(result);
this.ApplyPreResponseModules(context);
context.Response.Close();
}
catch (Exception ex)
{
this.LogErrors(ex);
}
}
乾杯羅布 - 這讓我過度了! – CameraSchoolDropout 2010-11-17 12:17:31