在我们的一项 ASP.NET Core 服务中,我们注意到每次请求后内存都在增加。它在 2 天内达到约 2GB。
我试图调查这个问题,我发现这个问题(可能)是垃圾收集器没有被触发。
为了使调查更容易,我尝试使用一个简单的 Web API 应用程序(Dotnet Core 2.1 版,在 Debug & Release/Self contains & IIS Express 中从 Visual Studio 模板创建)来了解情况
这个全新的应用程序有同样的问题。 每个请求的内存都会增加,并且永远不会被释放,如下图所示。
在系统内存不足的情况下,GC 得到 triggered 但内存永远不会消失。这是正常的吗?
因为这很奇怪,所以我在 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>true</ServerGarbageCollection>
</PropertyGroup>
关于c# - 每次请求都会增加 ASP.NET Core 内存,而 GC 不会释放它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51388701/