【问题标题】:ASP.NET Streaming Output: 1 single big chunk vs X smaller chunks?ASP.NET 流输出:1 个大块与 X 个小块?
【发布时间】:2013-04-30 02:21:56
【问题描述】:

使用 .NET 4.0、IIS 7.5 (Windows Server 2008 R2)。我想流出大约 10 MB 的二进制内容。内容已经在 MemoryStream 中。我想知道 IIS7 是否会自动分块输出流。从客户端接收流,这两种方法有什么区别:

//#1: Output the entire stream in 1 single chunks
Response.OutputStream.Write(memoryStr.ToArray(), 0, (int) memoryStr.Length);
Response.Flush();

//#2: Output by 4K chunks
byte[] buffer = new byte[4096];
int byteReadCount;
while ((byteReadCount = memoryStr.Read(buffer, 0, buffer.Length)) > 0)
{
   Response.OutputStream.Write(buffer, 0, byteReadCount);
   Response.Flush();
}

提前感谢您的帮助。


我没有尝试您传递原始数据流的第二个建议。内存流确实是从 Web 请求的响应流中填充的。这是代码,

HttpWebRequest webreq = (HttpWebRequest) WebRequest.Create(this._targetUri);
using (HttpWebResponse httpResponse = (HttpWebResponse)webreq.GetResponse())
{
   using (Stream responseStream = httpResponse.GetResponseStream())
   {
      byte[] buffer = new byte[4096];
      int byteReadCount = 0;
      MemoryStream memoryStr = new MemoryStream(4096);
      while ((byteReadCount = responseStream.Read(buffer, 0, buffer.Length)) > 0)
      {
         memoryStr.Write(buffer, 0, byteReadCount);
      }
      // ... etc ... //
   }
}

你认为它可以安全地将 responseStream 传递给 Response.OutputStream.Write() 吗?如果是,你能建议一种经济的方式吗?如何将 ByteArray + 确切的流长度发送到 Response.OutputStream.Write()?

【问题讨论】:

  • 您会多次提供该内容吗?

标签: asp.net outputstream


【解决方案1】:

第二个选项是最好的,因为 ToArray 实际上会创建存储在 MemoryStream 中的内部数组的副本。

但是,您也可以最好使用memoryStr.GetBuffer(),它将返回对该内部数组的引用。在这种情况下,您需要使用 memoryStr.Length 属性,因为 GetBuffer() 返回的缓冲区通常大于存储的实际数据(它是逐块分配的,而不是逐字节分配的)。

请注意,最好将原始数据作为流直接传递到 ASP.NET 输出流,而不是使用中间 MemoryStream。这首先取决于您如何获取二进制数据。

如果您经常提供完全相同的内容,另一种选择是将此 MemoryStream 保存到物理文件(使用 FileStream),并在所有后续请求中使用 Response.TransmitFile。 Response.TransmitFile 正在使用低级别的 Windows 套接字层,没有什么比发送文件更快了。

【讨论】:

  • 非常感谢先生的详尽回答。我已经使用 memoryStr.GetBuffer() 应用了您的建议。刚刚进行了回归测试,效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多