这个问题涉及到在另一张贴在这里评论: 取消实体框架查询
我将重现代码示例从那里净度:
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();
我不能作出这样的表示注释的意义
不要使用使用,因为它会导致竞争条件
entities
是一个局部变量,如果代码被另一个线程上重新输入不会被共享,并在同一个线程内,它似乎完全安全的(实际上等同于给定的代码),以分配给它里面的“使用”的声明以通常的方式,而不是人工做的事情与尝试/最后。 任何人都可以告诉我吗?