创建数组时SystemOutOfMemoryException

Use*_*999 5 .net vb.net arrays io

我正在SystemOutOfMemoryException创建一个数组.然而length我的阵列does not超过了Int32.MaxValue.

这是代码(请不要判断代码,不是我的代码至少7年)

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, 0, bytes)
        objInfo.content = data
    End If
Catch ex As Exception
    Throw ex
Finally
    myFileStream.Close()
End Try
Run Code Online (Sandbox Code Playgroud)

根据这个问题" .NET数组的SO最大尺寸 ",这问题" 的阵列的最大lenght "的最大长度是2,147,483,647 elements Or Int32.MaxValue而且maximum size2 GB

所以我的总数length of my array is well within the limits(3.08亿<20亿),my size is way smaller然后是2 GB(文件大小为298 mb).

问: 所以我的问题,关于数组还有什么可能导致MemoryOutOfMemoryException

注意:对于那些想知道服务器仍然有一些10GB的免费ram空间

注2:按照dude的建议,我在几次运行中监控了GDI-Objects的数量.进程本身永远不会超过计数1500个对象.

Aik*_*Aik 3

字节数组是序列中的字节。这意味着您必须分配与您的数组在一个块中的长度一样多的内存。如果您的内存碎片很大,即使您有 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) 
}
Run Code Online (Sandbox Code Playgroud)