Is it completely safe to use pattern of ReaderWriterLockSlim.EnterXXX() with consequent try-finally clause

不问归期 提交于 2019-12-04 05:55:58
Dean Ward

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();
   }
}

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.

Other exceptions are detailed in @hvd's post.

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

There are only three ways this could theoretically fail that I can think of:

  • ThreadAbortException you mentioned already. This is fairly easy to handle correctly: just make sure you never call Thread.Abort(). You almost certainly don't need to; there are almost always better ways of achieving the desired result.

    Only if you really, really, really need to call it, and the thread you're aborting is the one with a risk of keeping a lock open, place your entire block of code (from Enter to Exit) in a try...finally clause where the try-block is empty. Thread.Abort() will throw the ThreadAbortException only when the current finally handler finishes.

  • StackOverflowException is another possibility. It may happen during the call to ExitWriteLock. This is also fairly easy: when a stack overflow happens, the process is terminated. You cannot catch or handle this. Since the process is terminated, no other thread in your process will be keeping any lock open.

  • OutOfMemoryException might theoretically be thrown during the call to ExitWriteLock. Unlike StackOverflowException, this one is theoretically catchable. If you don't catch it, again the process will be terminated, and no other thread in your process will be keeping any lock open. If you do catch it, however, you cannot hope to handle this correctly, and chances are, your other threads will soon start throwing this exception as well.

In short, I wouldn't worry about it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!