gcAllowVeryLargeObjects 已设置但仍然导致 System.ArgumentOutOfRangeException

gcAllowVeryLargeObjects is set but still causing System.ArgumentOutOfRangeException

我有点没思路了。使用以下代码,我尝试实例化一个大于 2GB 的字节数组:

var b = Array.CreateInstance(typeof(byte), uint.MaxValue);

每次都会引发 System.ArgumentOutOfRangeException 异常,并显示消息 arrays larger then 2GB are not supported

我的 App.config 目前是这样的:

<?xml version="1.0" encoding="utf-8" ?>
   <configuration>
      <startup> 
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
      </startup>
      <runtime>
         <gcAllowVeryLargeObjects enabled="true" />
      </runtime>
   </configuration>

此外项目的目标平台是x64

如果有任何想法,我将不胜感激。如果有任何信息遗漏,我会尽快更新问题。

更新 1

我也试过了uint.MaxValue

只是为了完整性检查,您正在尝试分配 9.223 EB(艾字节)顺序内存块,即 9.223×10^9 GB(千兆字节)。很简单,但你甚至不能在 x64 机器上这样做,因为无论如何都会使用一些内存,那将是最大的。

改为尝试使用动态增长的列表:

var b = new List<byte>();

编辑:

对于字节数组和 single-byte 结构的数组,任何单一维度的最大索引为 2,147,483,591 (0x7FFFFFC7),对于其他类型为 2,146,435,071 (0X7FEFFFFF)。 - 来源:https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element

gcallowverylargeobjects-element的作用是你可以定义multi-dimentsional个超过2Gb的数组,如果是其他数据类型你可以分配2146435071*data_type_size内存。例如 int32 包含 4 个字节,因此它将是 8.586 GB(千兆字节)。

Single-dimensional 数组不能包含超过 int.MaxValue 个元素,即使它们可以大于 2gb <gcAllowVeryLargeObjects(例如 new int[int.MaxValue / 2] 是~4gb)。要解决这个问题,您必须创建一个二维数组,或者使用不同的类型,例如

public struct BytePair
{
    public byte First, Second;
}

然后创建一个 BytePair[] 大小的一半,相当于 byte[]