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

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

// 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; } } 

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

 The remote host closed the connection. The error code is 0x80072746 

这是完整的堆栈跟踪:

 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) 

我们从未有过证据表明用户在下载我们的文件时遇到问题,并且计划完全忽略此exception。

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

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

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

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

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

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

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

在web.config的httpRuntime元素中增加executionTimeout。

如果用户在慢速连接上下载大文件,请求最终会超时。

我发布这个答案是因为它可能会帮助他人并节省一些重要的时间。

在我的情况下, Response.Buffer = true在下载方法(在第一个语句中)解决了这个问题。

谢谢