难道是完全可以放心使用ReaderWriterLockSlim.EnterXXX()的模式与随之而来的try-finally从句从句、随之而来、放心、模式

由网友(ㄕ骵)分享简介:MSDN文档,并用许多例子 ReaderWriterLockSlim 类建议您使用以下方式:MSDN Documentation and many examples of using ReaderWriterLockSlim class recommends using the following pattern...

MSDN文档,并用许多例子 ReaderWriterLockSlim 类建议您使用以下方式:

MSDN Documentation and many examples of using ReaderWriterLockSlim class recommends using the following pattern:

cacheLock.EnterWriteLock();
try
{
    //Do something
}
finally
{
    cacheLock.ExitWriteLock();
}

不过我很好奇,如果它是完全安全的。难道某些异常会发生被收购后的锁定,但在此之前的尝试语句,这样,锁卡在锁定状态?最明显的候选人是 ThreadAbortException 。我理解这种情况的概率extreemely小,但后果是extreemely坏的 - 所以我认为这值得我们思考的。我不相信编译器理解这个模式和prevents打断线程处理器之前尝试语句。

But I'm curious if it's completely safe. Is it possible that some exception will happen after lock is acquired, but before the try statement so that lock is stuck in the locked state? The most obvious candidate is ThreadAbortException. I understand that probability of this situation is extreemely small, but the consequences are extreemely bad - so I think it worth thinking about it. I don't believe compiler understands this pattern and prevents processor from interrupting thread before try statement.

如果存在理论上的可能性,这code是不安全的,而且是有办法让它更安全?

If there is theoretical possibility that this code is unsafe, and is there ways to make it safer?

推荐答案

这可能是一个问题,显然是在一些高负载的情况。 这文章进入进一步,但它基本上可以归结为使用再加上最后收购及放一个空try块;解除锁定:

It can be an issue and apparently is in some high-load scenarios. This article goes into it further, but it basically boils down to using an empty try block coupled with a finally to acquire & release the lock:

var lockIsHeld = false;
try {
   try {
   }
   finally {
      rwl.EnterReadLock();
      lockIsHeld = true;
   }

   // Do work here
}
finally {
   if (lockIsHeld) {
      rwl.ExitReadLock();
   }
}

这个方法保证了你的锁始终获得和释放finally块,保证即使在的​​情况下运行 ThreadAbortException

This approach guarantees that your lock is always acquired and release as finally blocks are guaranteed to run even in the case of a ThreadAbortException.

其它异常详见@ HVD的帖子。

Other exceptions are detailed in @hvd's post.

我个人不会担心它,除非你真正看到这个问题在野外...

Personally I wouldn't worry about it unless you actually see this issue in the wild...

阅读全文

相关推荐

最新文章