问题描述
有人能向我解释如何以及为什么我们需要使用的Dispose()?这是默认的控制器模板自带的ASP.NET MVC 4.不宜在.NET中的垃圾回收器会自动踢的一部分,当从数据库中的对象,在这种情况下,数据是不再使用?
Can someone explain to me how and why do we need to use Dispose()? It's part of the default controller template that comes with ASP.NET MVC 4. Shouldn't the garbage collector in .NET automatically kick in when the object, in this case data from a database is no longer in use?
从数据库加载时,但它是正确的Dispose()方法应采用不正规的对象分配?
Is it correct that Dispose() should be used when loading from a database but not regular object assignments?
推荐答案
处置
时(在一次性模式,可以这么说),当与非托管资源处理。是的,.NET垃圾回收器将清理.NET管理的对象,但数据库连接是较低级别的对象不是由.NET框架管理。同样的事情与文件处理程序 - 使用Dispose模式,当你打开/写文件的实际文件句柄不被.NET托管
Dispose
is used (the Disposable pattern, so to speak) when dealing with unmanaged resources. Yes, the .NET Garbage Collector will clean up .NET managed objects, but database connections are lower level objects not managed by the .NET Framework. Same thing with file handlers -- use the Dispose pattern when you open/write to files as the actual file handle is not managed by .NET.
借助 MSDN文档描述 IDisposable的
,为什么你会实现它。
The MSDN documentation describes IDisposable
and why you'd implement it.
EF使用它,因为下面的的DbContext
是 DbDataConnection
,它与非托管资源的工作。在这些情况下,最好是实施的IDisposable
并办理清理相应的非托管资源。
EF uses it because underneath the DbContext
is a DbDataConnection
, which works with unmanaged resources. In those situations, it is best to implement IDisposable
and handle the clean up of your unmanaged resources accordingly.
这篇关于如何处置与实体框架工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!