写锁被释放,没有被关押 [英] Write lock being released without being held

查看:832
本文介绍了写锁被释放,没有被关押的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,即ReadWriterLockSlim抛出异常System.Threading.SynchronizationLockException - 要释放的写入锁定未经举行当我尝试执行ExitWriteLock()。据我所知,这是不应该的,因为进入try块后续线程将块,直到他们能够获得的锁。我失去了一些东西呢?

这个问题看起来非常相似,这其中,但是没有办法解决被张贴在那里。

  // code简化的例子。

公共类i18nService {
    内部静态ReaderWriterLockSlim cacheLock =新ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

    私人字符串ProcessText()
    {
        尝试 {
            cacheLock.EnterWriteLock();
            返回XYZ;
        }
        最后 {
            cacheLock.ExitWriteLock(); //错误是扔在这里。
        }
    }
}
 

非常感谢您的帮助: - )

解决方案

 尝试{
        cacheLock.EnterWriteLock();
        返回XYZ;
    }
    最后 {
        cacheLock.ExitWriteLock(); //错误是扔在这里。
    }
 

问:发生什么,如果 cacheLock.EnterWriteLock(); 失败

答:最后语句被执行

  • cacheLock.ExitWriteLock(); 被称为
  • 但是,我们没有锁定

试试这个:

 私人字符串ProcessText()
{
    cacheLock.EnterWriteLock();
    尝试 {
        返回XYZ;
    }
    最后 {
        cacheLock.ExitWriteLock(); //错误是扔在这里。
    }
}
 

presumably .NET的设计以这样一种方式,如果 EnterWriteLock()失败,锁被释放(或从未在所有举行)。

I have a situation whereby ReadWriterLockSlim is throwing the exception "System.Threading.SynchronizationLockException - The write lock is being released without being held." when I try to execute ExitWriteLock(). As far as I can tell, this shouldn't happen because subsequent threads that enter the try block will 'block' until they can obtain the lock. Am I missing something here?

The issue looks very similar to this one, however no solution was posted there.

//Code simplified for example. 

public class i18nService {
    internal static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

    private string ProcessText()
    {
        try {
            cacheLock.EnterWriteLock();
            return "xyz";
        }
        finally {
            cacheLock.ExitWriteLock(); // Error is throwing here. 
        }
    }
}

Thanks very much for your help :-)

解决方案

    try {
        cacheLock.EnterWriteLock();
        return "xyz";
    }
    finally {
        cacheLock.ExitWriteLock(); // Error is throwing here. 
    }

Q: What happens if cacheLock.EnterWriteLock(); fails?

A: The finally statement gets executed.

  • cacheLock.ExitWriteLock(); gets called
  • But we don't have the lock

Try this:

private string ProcessText()
{
    cacheLock.EnterWriteLock();
    try {
        return "xyz";
    }
    finally {
        cacheLock.ExitWriteLock(); // Error is throwing here. 
    }
}

Presumably .NET is designed in such a way that if EnterWriteLock() fails, the lock is released (or never held at all).

这篇关于写锁被释放,没有被关押的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆