相关疑难解决方法(0)

为什么尝试/最终而不是"使用"语句有助于避免竞争条件?

此问题涉及另一个帖子中的评论:取消实体框架查询

为清楚起见,我将从那里重现代码示例:

    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)

.net c# asynchronous entity-framework race-condition

24
推荐指数
2
解决办法
1999
查看次数

Monitor.TryEnter(object)和Monitor.TryEnter(object,ref bool)之间存在什么重要的区别?

似乎这些代码片段的行为应该相同:

1:Monitor.TryEnter(对象)

if (Monitor.TryEnter(lockObject))
{
    try
    {
        DoSomething();
    }
    finally
    {
        Monitor.Exit(lockObject);
    }
}
Run Code Online (Sandbox Code Playgroud)

2:Monitor.TryEnter(object,ref bool) - 在.NET 4.0中引入

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)方法的目的是什么?

.net multithreading synchronization monitor .net-4.0

10
推荐指数
1
解决办法
1730
查看次数