从InMemory数据库中删除数据时,内存使用不会减少

时间:2019-06-19 09:54:55

标签: asp.net-core in-memory-database

我在使用InMemory数据库的ASP.Net-Core中创建了示例Web API项目,它显示了奇怪的行为,即从数据库中删除内存时,内存使用没有改变(减少)。

我通过在TaskManager(taskmgr.exe)中观看“ .Net Core Host”进程来确认,但找不到原因。

我用招摇过头测试,下面是示例代码。 请告诉我我出了什么问题或误会。

[开发环境]

    Asp.Net Core(2.2.0)
    EntityFrameworkCore.InMemory(2.2.4)
    Swashbuckle.AspNetCore(4.0.1)

[ValuesController.cs]

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private MyDbContext _context;

        public ValuesController(MyDbContext context)
        {
            _context = context;
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id)
        {
            // Create about 200 MB Data of string
            var result = new Result()
            {
                Id = id,
                Data = new string('*', 100 * 1024 * 1024)
            };

            // Push 200 MB Data to InMemoryDB and save changes
            _context.Result.Add(result);
            _context.SaveChanges();
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            // find specific id result
            var result = _context.Result.Find(id);

            // if found, remove it and save changes
            if (result != null)
            {
                // ** Memory usage not change when removing **
                _context.Result.Remove(result);
                _context.SaveChanges();
            }
        }
    }

[MyDbContext.cs]

    public class MyDbContext : DbContext
    {
        /// <summary>
        /// DB context
        /// </summary>
        /// <param name="options"></param>
        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }

        /// <summary>
        /// Data set of Some Result
        /// </summary>
        public DbSet<Result> Result { get; set; }
    }

    /// <summary>
    /// Contains search result
    /// </summary>
    [Table("result")]
    public class Result
    {
        /// <summary>
        /// ID
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// Data
        /// </summary>
        public string Data { get; set; }
    }

[Program.cs]

    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var context = services.GetRequiredService<MyDbContext>();
            }

            host.Run();
        }

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

[Startup.cs]

    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_2);
            services.AddDbContext<MyDbContext>(opt =>
               opt.UseInMemoryDatabase("TestMemoryDb").UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v0.0.1", new Info
                {
                    Title = "InMemoryDBTest",
                    Version = "v0.0.1",
                    Description = "InMemoryDBTest",
                });
            });
        }

        // 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
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v0.0.1/swagger.json", "InMemoryDBTest V0.0.1");
                c.RoutePrefix = string.Empty;
            });
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }

1 个答案:

答案 0 :(得分:0)

vishwas-trivedi确认强制调用时GC确实会收集未使用的内存。 我将结束这个问题。 谢谢vishwas-trivedi

https://github.com/aspnet/EntityFrameworkCore/issues/16398