Is ReaderWriterLockSlim the right choice?

喜欢而已 提交于 2019-12-01 08:24:32

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

  • If you have a lot of locks and each of them is finer grained (locks for very small pieces of code) then ReaderWriterLockSlim or (spinlock).
  • Number of threads or contentions expected is high spinlock makes sense provided locking is fine grained.

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

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

Why don't you use a Queue to store the exceptions as they occur and spit them out in a background worker thread? Then you can just lock the enqueue/dequeue on each side. The window for collisions can be kept fairly small, and it's okay if your actual writing of the log data is behind, because order is preserved. If you want, you can wrap the Exception in some collection that includes the timestamp of when the item was enqueued so you can timestamp them appropriately.

Well, I think you shouldn't read without a lock on it, because you can read while the atomic operation are in course. The ReaderWriterLock seems better, as it garantees that no reader can enter when there's a write in process.

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