[英]Do I need to Close Connection when i use using?
I have the following code: 我有以下代码:
newCustomerDataSourceDataContext db = GetDataContext();
{
var tId = from t in db._CRM_Ticket_Headers
from p in db.CRM_Priority_LKPs
where t.created >= fromDate &&
t.created < toDate &&
t.priorityId == p.priorityId &&
t.statusId == status &&
t.employeeUserId == csrId
select t;
}
Do I have to close the Connection manually, if I add using
, and I am using Linq as the following: 如果using
添加,并且我使用Linq如下,是否必须手动关闭连接:
using (newCustomerDataSourceDataContext db = GetDataContext())
{
var tId = from t in db.CRM_Ticket_Headers
from p in db.CRM_Priority_LKPs
where t.created >= fromDate &&
t.created < toDate &&
t.priorityId == p.priorityId &&
t.statusId == status &&
t.employeeUserId == csrId
select t;
}
It depends on what you want to happen. 这取决于您要发生的事情。 If you use the using
block, the Dispose
method will be called on the context which will close the connection. 如果使用using
块,则将在上下文中调用Dispose
方法,这将关闭连接。 However, if your application is using lazy loading, that will no longer work. 但是,如果您的应用程序正在使用延迟加载,则将不再起作用。
No, it will be closed once you are out of using block. 不,一旦您退出使用块,它将关闭。 Resources are cleaned up when you leave that block. 离开该块时,将清理资源。
Should you dispose datacontect? 您应该处置数据保护吗?
The short answer; 简短的答案; no, you don't have to, but you should... 不,您不必这样做,但您应该...
DataContext holds state (for example, a SqlConnection and pointers to the objects you have retrieved). DataContext保持状态(例如,一个SqlConnection和指向您已检索到的对象的指针)。 These will eventually get cleaned up by the GC once you release all references, but some of these objects (for example, the underlying SqlConnection) may be holding resources that you typically want to release as soon as your are finished, rather than relying on the GC to clean up. 一旦释放所有引用,这些对象最终将被GC清除,但是其中某些对象(例如,基础SqlConnection)可能持有您通常希望在完成后立即释放的资源,而不是依赖于GC进行清理。
And as was mentioned it won't work nicely if you retrieve data in lazy mode 如前所述,如果您以惰性模式检索数据,它将不能很好地工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.