Response.OutputStream.Write中的"远程主机关闭了连接"

spa*_*zel 23 c# asp.net streaming

此代码将大文件传输给我们的用户:

                // Open the file.
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);


            // Total bytes to read:
            dataToRead = iStream.Length;

            // Read the bytes.
            while (dataToRead > 0)
            {
                // Verify that the client is connected.
                if (Response.IsClientConnected)
                {
                    // Read the data in buffer.
                    length = iStream.Read(buffer, 0, 10000);

                    // Write the data to the current output stream.
                    Response.OutputStream.Write(buffer, 0, length);

                    // Flush the data to the HTML output.
                    Response.Flush();

                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
Run Code Online (Sandbox Code Playgroud)

我们每隔一段时间就收到这个例外:

The remote host closed the connection. The error code is 0x80072746
Run Code Online (Sandbox Code Playgroud)

这是完整的堆栈跟踪:

Stack Trace:
   at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status, Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async)
   at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal)
   at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush)
   at System.Web.HttpResponse.Flush(Boolean finalFlush)
   at System.Web.HttpResponse.Flush()
   at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size)
   at System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at BIS.DocumentBus.Controls.DocumentViewer.StreamFile(String filepath)
Run Code Online (Sandbox Code Playgroud)

我们从来没有证据表明用户在下载我们的文件时遇到问题,并且计划完全忽略此异常.

知道这个问题的根源是什么?忽视是否安全?

Dav*_*vid 18

该异常意味着下载文件的客户端在文件下载完成之前中断了连接.即客户端导航到另一个页面,或者只是关闭浏览器.

我可能会尝试移动if (Response.IsClientConnected)你的线iStream.Read.即使你这样做了,我认为如果在OutputStream.Write方法仍在工作时断开连接,仍有可能收到此错误.

  • @ spaetzel - 如果这不能解决你的问题,你为什么把这篇文章标记为答案? (11认同)
  • 我无法通过取消下载来重现异常.我们甚至尝试在下载期间断开网络连接.两者都没有引发异常. (3认同)

Jon*_*nna 12

这有几个不同的可能原因.我能想到三个:

一个是用接近2GB的数据填充缓冲区,但这不应该是这种情况,因为你经常冲洗.

另一个确实是您之前接受的答案中描述的.它很难再现,所以我不认为它一定是错的.

另一种可能的情况,也就是我要打赌的情况,就是超出了executionTimeout,这会导致一开始就出现ThreadAbortException,但这又可能导致Flush()失败,这会导致注意到的异常