难道是完全可以放心使用ReaderWriterLockSlim.EnterXXX()的模式与随之而来的try-finally从句 [英] Is it completely safe to use pattern of ReaderWriterLockSlim.EnterXXX() with consequent try-finally clause

查看:235
本文介绍了难道是完全可以放心使用ReaderWriterLockSlim.EnterXXX()的模式与随之而来的try-finally从句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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...

这篇关于难道是完全可以放心使用ReaderWriterLockSlim.EnterXXX()的模式与随之而来的try-finally从句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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