C# EF DbContext内存未释放
我无法释放EF DbContext使用的进程内存。 尽管有dispose和GC.Collect,但我的应用程序并没有释放内存 我创建了一个小程序:C# EF DbContext内存未释放,c#,entity-framework,memory,garbage-collection,C#,Entity Framework,Memory,Garbage Collection,我无法释放EF DbContext使用的进程内存。 尽管有dispose和GC.Collect,但我的应用程序并没有释放内存 我创建了一个小程序: static void Main(string[] args) { var test = new TestDb(); System.Threading.Thread.Sleep(1000); // Here proc memory = 7 Mo test.Fill(); System.Threading.
static void Main(string[] args)
{
var test = new TestDb();
System.Threading.Thread.Sleep(1000);
// Here proc memory = 7 Mo
test.Fill();
System.Threading.Thread.Sleep(1000);
// Here proc memory = 58 Mo
test.Dispose();
System.Threading.Thread.Sleep(1000);
// Here proc memory = 37.8 Mo
test = null;
GC.Collect();
// Here proc memory = 37.8 Mo
// Why is not 0 here ???
System.Threading.Thread.Sleep(1000);
}
您可以通过我的评论显示内存使用情况
TestDb类:
public class TestDb : IDisposable
{
private List<TaskAction> _actions;
public void Fill()
{
using (var entities = new myEntities())
{
entities.Configuration.LazyLoadingEnabled = false;
_actions = entities.TaskActions.ToList();
}
}
public void Dispose()
{
_actions = null;
GC.Collect();
}
}
公共类TestDb:IDisposable
{
私人名单(行动);;
填空
{
使用(var entities=new myEntities())
{
entities.Configuration.LazyLoadingEnabled=false;
_actions=entities.TaskActions.ToList();
}
}
公共空间处置()
{
_actions=null;
GC.Collect();
}
}
如何释放所有已使用的内存
谢谢
如果我们只关注数据内存:运行时不会将内存返回操作系统,除非有充分的理由;如果您刚刚使用了{some amount memory},那么很有可能您会在一瞬间再次使用它,并且将它保持一段时间会更加有效
GC.Collect
只处理内部簿记,这样它就不必在短时间内要求操作系统提供更多内存。您可以做一些事情,使运行时在返回内存方面更具攻击性,但是。。。37Mb基本上什么都不是
此外,它仍然需要内存来存储内部.NET位(类型元数据、您加载的所有程序集、JIT、IL等)。做一些事情,任何带有EF(或任何其他库)的东西都会占用一些不会被释放的内存。由于您已经与数据库进行了交谈,现在可能还有一个连接池(托管和非托管)和一些与SQL相关的线程