.NET ReaderWriterLockSlim问题 [英] .NET ReaderWriterLockSlim issues

查看:109
本文介绍了.NET ReaderWriterLockSlim问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多写关于ReaderWriterLockSlim类,它允许多个读取和一个写入。所有这些(至少,我已经找到)告诉如何使用它没有太多的解释,为什么它是如何工作。标准code样品是:

There are lots written about the ReaderWriterLockSlim class which allows multiple read and a single write. All of these (at least that I had found) tell how to use it without much explanation why and how it works. The standard code sample is:

lock.EnterUpgradeableReadLock();

try
{
   if (test if write is required)
   {
      lock.EnterWriteLock();

      try
      {
          change the resourse here.
      }
      finally
      {
         lock.ExitWriteLock();
      }
   }
}
finally
{
   lock.ExitUpgradeableReadLock();
}

现在的问题是:如果升级锁定只允许一个线程进入其节,我为什么要在调用EnterWriteLock方法?如果我不会发生什么事?或者将要发生什么,而不是EnterUpgradeableReadLock如果我会打电话给EnterWriteLock并且将其写入到一个资源而不在所有使用升级的锁?

The question is: if upgradeable lock permits only a single thread to enter its section, why I should call EnterWriteLock method within? What will happen if I don't? Or what will happen if instead of EnterUpgradeableReadLock I will call EnterWriteLock and will write to a resource without using upgradeable lock at all?

推荐答案

使用的好处 EnterUpgradeableReadLock EnterReadLock 是,你可以肯定知道您检查,以确定是否进入写入锁定或没有条件不检查条件和实际进入写入锁之间切换。这避免了可能需要定期锁定 S中的复制:

The upside of using EnterUpgradeableReadLock over EnterReadLock is that you can know for sure that the condition that you check in order to determine whether to enter the write lock or not does not change between checking the condition and actually entering the write lock. This avoids the duplication that may be needed with regular locks:

if (whatever-condition)
{
    lock (_lockObject)
    {
        // the condition may have changed betwen the check and the lock; verify
        // that the condition is still valid
        if (whatever-condition)
        {
            // do the stuff
        }
    }
}

与此同时,它的没有的块调用 EnterReadLock ,所以其他线程可能仍然可以读取$其他部分的访问C $ C(以及呼叫将,当然,阻塞调用 EnterWriteLock ,直到他们释放读锁)。

At the same time, it does not block calls to EnterReadLock, so other threads may still get read access in other parts of the code (and those calls will, of course, block the call to EnterWriteLock until they release the read locks).

这篇关于.NET ReaderWriterLockSlim问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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