Why ASP Net Core 2.2 do not release memory?

后端 未结 2 1701
自闭症患者
自闭症患者 2020-12-24 13:46

I\'m testing ASP Net Core 2.2 using default project made from:

Visual Studio > File > New > Project > ASP NET Core Web Application > Next > Create. Press IIS

2条回答
  •  粉色の甜心
    2020-12-24 14:12

    I was struggling with the same issue. After a little research i found that .NET Core allocating new memory space if it can. It will be released if it is necessary, but this release is more resource demanding than the other releasing, because you have to use the GC this way:

    GC.Collect(2, GCCollectionMode.Forced, true);
    GC.WaitForPendingFinalizers();
    

    My solution was to create a middleware:

    using Microsoft.AspNetCore.Http;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace RegisterValidator
    {
        public class GCMiddleware
        {
            private readonly RequestDelegate _next;
    
            public GCMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext httpContext)
            {
                await _next(httpContext);
                GC.Collect(2, GCCollectionMode.Forced, true);
                GC.WaitForPendingFinalizers();
            }
        }
    }
    

    EDIT: this middleware will provide a GC.Collect after every call.

    And register it in the Configure() method in Startup.cs:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider service, ILoggerFactory loggerFactory)
        {
    
            app.UseMiddleware();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
    
            app.UseStaticFiles();
            //app.UseHttpsRedirection();
            app.UseMvcWithDefaultRoute();
    
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("\"No ");
    
            });
        }
    

    Maybe there is another solution but I haven't found it yet. I hope it helps.

    Edit: If you aren't sure that the memory usage is because there is a huge amount of allodated space of some other issue you can use dotMemory that will profile your memory usage with more detail than your Visual Studio.

提交回复
热议问题