本文介绍了是ReaderWriterLockSlim正确的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个全球性的错误处理/记录器在Windows Azure中运行的应用程序。当错误的应用程序时,许多操作所执行的需要发生原子。我需要prevent被记录,直到previous一个人完成了一个错误。同时,我想读取日志的需要发生。

I'm writing a global error handler/logger for applications running in Windows Azure. When an error occurs in the application, a number of operations are performed that need to happen atomically. I need to prevent an error from being logged until the previous one has completed. Meanwhile, I want reads of the logs to occur as needed.

我最初的想法是使用监视器/锁,仅锁定错误写。这样的读操作是不抑制在所有。我在想,虽然ReaderWriterLockSlim是否会更合适。我不能说我的真正的理解一种方法对两者之间的数值。

My initial thought was using a Monitor/lock and lock only the error writes. That way the reads aren't inhibited at all. I was wondering though whether a ReaderWriterLockSlim would be more appropriate. I can't say I truly understand the value between one approach vs. the other.

我应该创建一个ReaderWriterLockSlim,并完成类似下面的下面(与读取被包裹在EnterReadLock)...

Should I create a ReaderWriterLockSlim and do something like the following below (with reads being wrapped in EnterReadLock)...

public static void LogError(Exception exception)
{
    _lock.EnterWriteLock();

    ...

    _lock.ExitWriteLock();
}

或者,我只是做类似下面,只锁定写入部分:

Or do I simply do something like the following, only locking the write sections:

public static void LogError(Exception exception)
{
     lock (someStaticLock)
     {
        ...
     }
}

任何想法/意见将是多少AP preciated。

Any thoughts/advice would be much appreciated.

推荐答案

确定,完全取决于它的资源争是如何预期。下面是一个简单的决定,我的基础上会做什么呢,我锁定了多少锁定。

OK, it entirely depends on how resource contention is expected. Following is a simple decision I would make based on what I'm locking and how much locking.

ReaderWriterLockSlim是使用螺旋锁来实现,因此,如果有长锁定的资源(在这种情况下,编写文本)它会导致因为纺丝到一个更差的性能通过等待线程。在下列情况下,这就是说,它非常有用的工具。

ReaderWriterLockSlim is implemented using a spinlock, therefore if you have long locking resources (writing text in this case) it would lead to a worse performance because of spinning by waiting threads. That said, its very useful tool in following situations.

  • 如果您有大量锁定,他们每个人的更细粒度(锁非常小件code),然后ReaderWriterLockSlim或(自旋锁)。
  • 预计线程或争论的数字是高自旋锁使得提供感锁定是细粒度的。

锁或监视器是最适合当你的论点是粗粒,你知道争或锁的数量较低。

Lock or Monitor is best suited when your contentions are coarsegrained and you know that contentions or number of locks are lower.

ReaderWriterLockSlim相对比ReaderWriterLock快ATLEAST 3-5倍。

ReaderWriterLockSlim is comparatively faster than ReaderWriterLock atleast 3-5 times.

这篇关于是ReaderWriterLockSlim正确的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 22:01