You need to enable JavaScript to run this app. 如何在C#单元测试中配置gcAllowVeryLargeObjects运行时参数?
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#单元测试中配置gcAllowVeryLargeObjects运行时参数?

解决方案

以下是不同场景下的可行配置方式:

1. .NET Framework 单元测试项目配置

  • 在单元测试项目根目录新建app.config文件,填入以下内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>
  • 右键点击该文件,选择「属性」,将「复制到输出目录」选项设置为「如果较新则复制」,确保测试运行时能读取到配置。

2. .NET Core/.NET 5+ 单元测试项目配置

有两种可选方式:

方式A:通过运行时配置文件设置

  • 在单元测试项目根目录新建[测试项目名称].runtimeconfig.json文件,填入以下内容:
{
  "runtimeOptions": {
    "configProperties": {
      "System.GC.AllowVeryLargeObjects": true
    }
  }
}
  • 同样将文件的「复制到输出目录」属性设置为「如果较新则复制」。

方式B:通过代码动态配置

可以在测试程序集的全局初始化方法中注入配置,该方式仅支持.NET Core 3.0及以上版本,不需要额外添加配置文件:

  • MSTest 示例:
[AssemblyInitialize]
public static void TestAssemblyInit(TestContext context)
{
    AppContext.SetSwitch("System.GC.AllowVeryLargeObjects", true);
}
  • xUnit 示例:
public class TestAssemblyFixture : IAssemblyFixture<TestAssemblyFixture>
{
    public TestAssemblyFixture()
    {
        AppContext.SetSwitch("System.GC.AllowVeryLargeObjects", true);
    }
}

额外排查注意项

  • 必须将单元测试项目的平台目标设置为x64:32位进程存在2G内存上限,即使开启该参数也无法创建超过2G的单对象,需要在项目属性的「生成」页中将平台目标修改为x64,不要使用AnyCPU。
  • 确认Newtonsoft.Json版本不低于13.0.1:部分旧版本存在大数组反序列化的硬编码长度限制,升级到最新版本即可解除该限制。

内容的提问来源于stack exchange,提问作者NilesDavis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 03:36:05