c# - 每次请求时 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" };
}
}
解决方案
我不知道您是否找到了解决方案,但我的 asp.net core 5.0 应用程序遇到了同样的问题。评论中提到的 DarthVader 解决方案对我有用。刚刚在项目文件中添加了以下部分:
<PropertyGroup>
<ServerGarbageCollection>false</ServerGarbageCollection>
</PropertyGroup>
推荐阅读
- meta-tags - URL预览图片策略
- sql - 从选择中更新,否则如果在 PostgreSQL 中为空,则恢复为其他选择
- python - Forbidden:请求被禁止——授权无济于事([GET] https://api.anaconda.org/user -> 403)
- c# - Visual Studio 编译器错误(不能使用逗号)
- python - 计算图中演员的凯文培根数
- android - 我需要将当前日期与其他数据一起添加到 firebase Realtime 数据库,并在 kotlin android 中检索所有带有日期的数据
- algorithm - 将数量分配给数组元素以使对的差异最小的最快方法?
- python - 训练停留在自定义数据集上的简单 Pytorch 模型上
- c# - T4 模板中的继承
- python - Python Matplotlib:向子图添加水印