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

我在安装了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。所以我想知道是否需要设置一些全局设置才能使其正常工作?



郎朗坤
浏览 1299回答 3
3回答

慕姐8265434

我知道这很旧,但是我想知道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. }
打开App,查看更多内容
随时随地看视频慕课网APP