为什么会抛出OutOfMemory?

时间:2012-11-08 14:34:23

标签: c# .net 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);
        }
    }
}

为什么在AllocHGlobal调用成功后会获得OutOfMemory?

1 个答案:

答案 0 :(得分:6)

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