首页 > 解决方案 > 每次请求时 ASP.NET Core 内存都会增加,而 GC 不会释放它

问题描述

在我们的一项 ASP.NET Core 服务中,我们注意到每次请求后内存都在增加。它在 2 天内达到约 2GB。

我试图调查这个问题,我发现问题(可能)与垃圾收集器有关,它没有被触发。

为了使调查更容易,我尝试使用一个简单的 Web API 应用程序查看情况如何(从 Visual Studio 模板创建的 Dotnet Core 版本 2.1,在调试和发布/自包含和 IIS Express 中)

这个全新的应用程序有同样的问题。每个请求的内存都会增加,并且永远不会被释放,如下图所示。

在此处输入图像描述

如果系统内存不足,则会触发GC,但内存永远不会下降。这是正常的吗?

因为这很奇怪,所以我在 Framework 4.6 上用一个简单的 ASP.NET 做了同样的测试。内存被释放

这很奇怪,不能接受。谁能向我解释一下 ASP.NET Core 内存发生了什么?

编辑:

根据要求,这是我的代码,一个从 Visual Studio 生成的非常基本的 ASP.NET Core:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseMvc();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();
}

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

}

标签: c#asp.net-corememory-leaksgarbage-collection

解决方案


我不知道您是否找到了解决方案,但我的 asp.net core 5.0 应用程序遇到了同样的问题。评论中提到的 DarthVader 解决方案对我有用。刚刚在项目文件中添加了以下部分:

<PropertyGroup>
    <ServerGarbageCollection>false</ServerGarbageCollection>
</PropertyGroup>

推荐阅读