我在创建数组时遇到SystemOutOfMemoryException.然而,我的数组的长度不超过Int32.MaxValue.
Dim myFileToUpload As New IO.FileInfo(IO.Path.Combine(m_Path,filename)) Dim myFileStream As IO.FileStream Try myFileStream = myFileToUpload.OpenRead Dim bytes As Long = myFileStream.Length //(Length is roughly 308 million) If bytes > 0 Then Dim data(bytes - 1) As Byte // OutOfMemoryException is caught here myFileStream.Read(data,bytes) objInfo.content = data End If Catch ex As Exception Throw ex Finally myFileStream.Close() End Try
根据这个问题“SO Max Size of .Net Arrays”和这个问题“Maximum lenght of an array”,最大长度为2,147,483,647个元素或Int32.MaxValue,最大大小为2 GB
所以我的阵列的总长度完全在限制范围内(3.08亿< 20亿),而且我的大小也小于2 GB(文件大小为298 mb). 题:
所以我的问题,关于数组还有什么可能导致MemoryOutOfMemoryException?
注意:对于那些想知道服务器仍然有一些10GB的免费ram空间
注2:在dude’s advice之后,我在几次运行中监控了GDI对象的数量.进程本身永远不会超过计数1500个对象.
字节数组是序列中的字节.这意味着你必须分配这么多内存,因为你的数组在一个块中是长度的.如果你的内存碎片大于系统无法分配内存,即使你有X GB内存空闲.
例如,在我的机器上,我不能在一个阵列中分配超过908 000 000字节,但如果存储在更多阵列中,我可以毫无问题地分配100 * 90 800 000:
// alocation in one array byte[] toBigArray = new byte[908000000]; //doesn't work (6 zeroes after 908) // allocation in more arrays byte[][] a=new byte[100][]; for (int i = 0 ; i<a.Length;i++) // it works even there is 10x more memory needed than before { a[0] = new byte[90800000]; // (5 zeroes after 908) }