为了账号安全,请及时绑定邮箱和手机立即绑定

填充MemoryStream时出现OutOfMemoryException:在16GB系统上分配

填充MemoryStream时出现OutOfMemoryException:在16GB系统上分配

郎朗坤 2020-02-02 15:30:06
我在安装了16GB RAM的64位Windows 7计算机上的开发IIS服务器(来自VS2010 IDE)上运行以下方法:public static MemoryStream copyStreamIntoMemoryStream(Stream stream){    long uiLen = stream.Length;    byte[] buff = new byte[0x8000];    int nSz;    MemoryStream ms = new MemoryStream();    try    {        while ((nSz = stream.Read(buff, 0, buff.Length)) != 0)        {            ms.Write(buff, 0, nSz);        }    }    finally    {        Debug.WriteLine("Alloc size=" + ms.Length);    }    return ms;}我得到了System.OutOfMemoryException这一行:ms.Write(buff, 0, nSz);分配268435456字节时抛出该错误:分配大小= 268435456这是0x10000000或256 MB。所以我想知道是否需要设置一些全局设置才能使其正常工作?
查看完整描述

3 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

我知道这很旧,但是我想知道Stream.CopyTo()方法是否不能解决小于int.MaxValue的流长度的内存分配问题?在这种情况下,以下代码可能不太容易出现OutOfMemory异常: if (int.MaxValue >= memoryStream.Length) { MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); memoryStream.Capacity = (int) memoryStream.Length; // Optional but helps eliminate null padding. }

查看完整回答
反对 回复 2020-02-02
  • 3 回答
  • 0 关注
  • 1288 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信