这个问题与此处另一个帖子中的评论有关:取消实体框架查询
为了清楚起见,我将从那里复制代码示例:
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 手动执行操作。任何人都可以启发我吗?