Avoiding the LOH when reading a binary

纵然是瞬间 提交于 2019-12-02 09:26:41

The memory stream holds an internal array fo the whole data (which you return in the end). It doesn't matter that you read in chunks of 2048 bytes as long as you keep concatenating to the memory stream. If you need to return the data as an array containing the entire file, then you will end up often creating that array the large object heap.

If the destination (a BLOB field or similar) does not allow you to pass in the data in any other way than a single byte array, then you can't get around allocating a byte array that holds all the data.

The best way of transferring data to the destination is of course if the destination also supports a stream semantic.

int Transfer(Stream source, Stream target)
{
   byte buffer = new byte[BufSize];
   int totalBytesTransferred = 0;
   while ((bytesRead = source.Read(buffer, 0, BufSize)) > 0)
   {
      target.Write(buffer, 0, bytesRead);
      totalBytesTransferred += bytesRead;       
   }
   return totalBytesTransferred;
}

If this is possible depends on whether the target (Database BLOB for example) supports opening a stream to the target or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!