简体   繁体   English

EF Core上下文未处理变更跟踪实体

[英]EF Core context not disposing of change tracking entities

Using EF Core 2.1 to insert 135k records. 使用EF Core 2.1插入135k记录。 Once the request is finished, I would expect the context to be disposed of and along with it, the ChangeTracking entities to be cleared, however, it's holding on to all 135k records and using a lot of memory in the process. 请求完成后,我希望可以处理上下文,并与它一起清除ChangeTracking实体,但是,它将保留所有135k记录并在此过程中使用大量内存。

We are using ASP.NET Core 2.1 and injecting the EF Context from the DI container. 我们正在使用ASP.NET Core 2.1,并从DI容器注入EF上下文。 Since the DI container should dispose of the scoped context at the end of the request, it should not be holding on to these values. 由于DI容器应在请求结束时处理范围内的上下文,因此它不应保留这些值。 Even calling dispose manually at the end of the controller does not seem to affect the change tracking entities. 甚至在控制器末端手动调用Dispose似乎也不会影响更改跟踪实体。

Below is the output of the heap view of the memory usage after the request has finished. 下面是请求完成后内存使用情况的堆视图的输出。 Diving into the path, I'm seeing a lot of EF Core classes and strangely seeing a EntityQueryable instance for a different entity ( System vs InvoicePendingItem ). 深入研究路径,我看到了很多EF Core类,并且奇怪地看到了另一个实体( System vs InvoicePendingItem )的EntityQueryable实例。

堆


The context is being registered in Startup.cs : 上下文正在Startup.cs中注册:

services.AddDbContext<EFContext>(options => options.UseMySql(
  GetDBConnectionString()
));

Seems to be a question about: How should I manage DbContext Lifetime in MVC Core? 似乎是一个问题: 我应该如何在MVC Core中管理DbContext生存期?

As for change tracking, it is enabled by default and is removed when you dispose of the context. 对于更改跟踪,默认情况下已启用它,并且在处置上下文时将其删除。 However you can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false 但是,您也可以通过将DbContext的AutoDetectChangesEnabled属性设置为false来禁用更改跟踪。

context.Configuration.AutoDetectChangesEnabled = false;

Additionally, when you insert +100k items you should do that in batches of for example 2k for performance and memory reasons. 此外,当插入+ 100k项时,出于性能和内存方面的原因,应分批执行,例如2k。

You can implement the IDispose interface in your classes correctly and manage how the class will be destroyed when it is no longer used, implement the interface and use the Dispose Pattern. 您可以正确地在您的类中实现IDispose接口,并管理在不再使用该类时如何销毁该类,实现该接口并使用Dispose Pattern。

在此处输入图片说明

Read about in this documentation: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose 在此文档中阅读有关内容: https : //docs.microsoft.com/zh-cn/dotnet/standard/garbage-collection/implementing-dispose

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM