正在处理实体框架上下文对象 [英] Is Disposing of Entity Framework context object required

查看:73
本文介绍了正在处理实体框架上下文对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在WCF服务方法中使用实体框架与数据库进行通信,最近我们在服务代码上运行代码审查工具。像往常一样,我们通过工具得到了许多审查提案,许多评论意见建议处理实体框架上下文对象。所以,我的问题是如果我在一个方法中使用一个Entity Framework上下文对象,一旦我出来的方法,GC不清理上下文对象?我们需要明确地处理上下文对象吗?

解决方案

只需: DbContext 实现 IDisposable ,因此,一旦完成,您应该手动处理。



需要处理它,因为GC将最终收集,但是GC不是确定性的:你永远不知道什么时候最终将是。在它被处置之前,它将保存未被使用的资源 - 例如,它可能仍然具有开放的数据库连接。在GC运行之前,这些资源不会被释放,除非您手动处理。根据具体细节,您可能会发现您已经不必要地阻止了网络资源,文件访问,您一定会保留比您需要的更多的内存。



还有一个潜在命中:当您手动处理对象时,GC通常不需要调用该对象上的Finalizer(如果有的话)。如果您离开GC自动处理一个对象与Finalizer,它会将对象放在一个Finalizer队列中,并将自动将对象提升到下一个GC生成。这意味着具有终结器的对象总是会在GCed之前比它需要的数量级更长(因为连续的GC代码被收集得较少)。



(有用的参考。)


We are using entity framework for communication with database in our WCF service methods, recently we run the code review tool on our service code. As usual we got many review proposals by tool and many review comments were suggesting to dispose the Entity Framework context object. So, my question is if I use a Entity Framework context object within a method and once I come out of the method, GC doesn't clean up the context object ? do we need to explicitly dispose context object ?

解决方案

Simply: DbContext implements IDisposable, therefore you should dispose of it, manually, as soon as you're done with it.

You don't need to dispose of it, because the GC will collect it eventually, but the GC isn't deterministic: you never know when "eventually" will be. Until it's disposed, it will be holding resources that aren't in use - for example, it may still have an open database connection. Those resources aren't freed until the GC runs, unless you dispose manually. Depending on specific details you may find that you have unnecessarily blocked network resources, file accesses, and you will certainly be keeping more memory reserved than you need to.

There's a further potential hit, too: when you dispose of an object manually, the GC doesn't typically need to call the Finalizer on that object (if there is one). If you leave the GC to automatically dispose of an object with a Finalizer, it'll place the object in a Finalizer Queue - and will automatically promote the object to the next GC generation. This means that an object with a finalizer will always hang around for orders of magnitude longer than it needs to before being GCed (as successive GC generations are collected less frequently). DBContext would likely fall into this category as the underlying database connection will be unmanaged code.

(Useful reference.)

这篇关于正在处理实体框架上下文对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆