2

我正在尝试 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?

4

1 回答 1

6

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

于 2012-11-08T14:36:50.060 回答