为什么会抛出OutOfMemory?

Otá*_*cio 2 .net c# memory-management

我正在试验Marshal.AllocHGlobal并发现令人费解的是这段代码不会成功,而是抛出一个OutOfMemory异常:

namespace HAlloc
{
    using System;
    using System.IO;
    using System.Runtime.InteropServices;

    class Program
    {
        static void Main(string[] args)
        {
            // large file ~ 800MB
            string fileName = @"largefile.bin";
            FileInfo fileInfo = new FileInfo(fileName);

            // allocation succeeds
            IntPtr p = Marshal.AllocHGlobal((int)fileInfo.Length);

            // OutOfMemory exception thrown here:
            Marshal.Copy(File.ReadAllBytes(fileName), 0, p, (int)fileInfo.Length);
            Marshal.FreeHGlobal(p);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当AllocHGlobal调用成功时,为什么会获得OutOfMemory?

Sno*_*ear 6

原因File.ReadAllBytes(fileName)还必须读取导致额外~800 MB的文件