Использование памяти не уменьшается при удалении данных из базы данных InMemory - PullRequest
1 голос
/ 19 июня 2019

Я создал пример проекта Web API в ASP.Net-Core, который использует базу данных InMemory, и он показывает странное поведение, при котором использование памяти не изменялось (уменьшалось) при удалении ее из базы данных.

Я подтвердил при просмотре ".«Net Core Host» в TaskManager (taskmgr.exe), и я не могу найти причину.

Я протестировал swagger, и мой пример кода приведен ниже.Скажите, пожалуйста, в чем я ошибаюсь или ошибаюсь.

[Разработка среды]

    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 голосов
/ 10 июля 2019

Вишвас-Триведи подтвердил, что GC собирает неиспользуемую память при принудительном вызове. Я закрою этот вопрос. Спасибо, Вишвас-Триведи

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

...