写入HttpListenerResponse时发生I / O错误

时间:2019-06-03 19:20:24

标签: c#

在将输出写入HttpListenerResponse时,服务器将引发I / O操作异常终止。仅当请求和响应之间的延迟(即DoMoreWork()花费的时间)超过4-5分钟时才会发生。发生了一些超时,但是我看不到与此相关的任何日志。

我在TimeOutManager中设置了各种超时时间,尝试在客户端和服务器端打开/关闭KeepAlive,在System32 / LogFiles / Httperr中检查了日志,但没有找到任何可能导致此错误的内容。

OS是Windows Server 2016,.Net框架是4.7。

例外:

System.Net.HttpListenerException (0x80004005): The I/O operation has been aborted because of either a thread exit or an application request
at System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)

Windows服务代码:

using (HttpListener listener = new HttpListener())
{
    listener.Prefixes.Add(/*port*/);
    listener.TimeoutManager.IdleConnection = TimeSpan.FromMinutes(15);
    listener.Start();

    while (true)
    {
        HttpListenerContext context = listener.GetContext();
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), context);
        Thread.Sleep(100);
    }
    listener.Stop();
}

public static void DoWork(object threadContext)
{
    HttpListenerContext context = threadContext as HttpListenerContext;
    byte[] data = DoMoreWork();
    context.Response.ContentLength64 = data .Length;

    //Does not help
    //context.Response.SendChunked = false;
    //context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet;
    context.Response.OutputStream.Write(data, 0, data.Length); //THROWS
    context.Response.StatusCode = 200;
}

0 个答案:

没有答案