此问题涉及另一个帖子中的评论:取消实体框架查询
为清楚起见,我将从那里重现代码示例:
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 …Run Code Online (Sandbox Code Playgroud) 似乎这些代码片段的行为应该相同:
if (Monitor.TryEnter(lockObject))
{
try
{
DoSomething();
}
finally
{
Monitor.Exit(lockObject);
}
}
Run Code Online (Sandbox Code Playgroud)
bool lockAcquired;
try
{
Monitor.TryEnter(lockObject, ref lockAcquired);
if (lockAcquired)
{
DoSomething();
}
}
finally
{
if (lockAcquired)
{
Monitor.Exit(lockObject);
}
}
Run Code Online (Sandbox Code Playgroud)
我从MSDN文档中看到有关带ref bool参数的重载:
如果因为抛出异常而未执行锁定,则在此方法结束后,为lockTaken参数指定的变量为false.这允许程序在所有情况下确定是否有必要释放锁.
但文档还指出,仅使用object参数的重载不会引发除例外之外的任何异常ArgumentNullException.因此,它好像如果一个例外是在代码片段抛出1以上,它只能是因为lockObjectIS null,在这种情况下没有作出锁定(并TryEnter会一直返回false)反正,所以Monitor.Exit就没有必要了电话.
很明显,他们不会毫无理由地引入这种过载.那么该Monitor.TryEnter(object, ref bool)方法的目的是什么?