【发布时间】:2013-01-27 15:22:11
【问题描述】:
此问题与此处另一个帖子中的评论有关:Cancelling an Entity Framework Query
为了清楚起见,我将从那里复制代码示例:
var thread = new Thread((param) =>
{
var currentString = param as string;
if (currentString == null)
{
// TODO OMG exception
throw new Exception();
}
AdventureWorks2008R2Entities entities = null;
try // Don't use using because it can cause race condition
{
entities = new AdventureWorks2008R2Entities();
ObjectQuery<Person> query = entities.People
.Include("Password")
.Include("PersonPhone")
.Include("EmailAddress")
.Include("BusinessEntity")
.Include("BusinessEntityContact");
// Improves performance of readonly query where
// objects do not have to be tracked by context
// Edit: But it doesn't work for this query because of includes
// query.MergeOption = MergeOption.NoTracking;
foreach (var record in query
.Where(p => p.LastName.StartsWith(currentString)))
{
// TODO fill some buffer and invoke UI update
}
}
finally
{
if (entities != null)
{
entities.Dispose();
}
}
});
thread.Start("P");
// Just for test
Thread.Sleep(500);
thread.Abort();
我无法理解上面的评论
不要使用 using,因为它会导致竞争条件
entities 是一个局部变量,如果代码在另一个线程上重新输入,则不会被共享,并且在同一个线程中,将它分配给它看起来非常安全(实际上等同于给定的代码)以通常的方式使用“使用”语句,而不是使用 try/finally 手动执行操作。谁能赐教?
【问题讨论】:
-
你应该问原作者。这对我来说毫无意义。
-
你为什么不问问那个代码的创建者? (FTFY)
-
这是我的第一个想法,但很遗憾,我找不到联系他的方法,他的博客上没有电子邮件,也无法在此处或 MSDN 论坛上发送个人消息,我可以揣摩(但如果我很昏暗并错过了它,请指出我正确的方向!)
标签: c# .net entity-framework asynchronous race-condition