开发者

Question about locking strategy (C# / .NET 3.5 SP1)

I need to write a class that hold as Dictionary. The Dictionary will be accessed by multiple threads. Each access will be very short.

I expect:

  • every minute an access that adds or removes entries
  • Every 2 sec. I need to create a copy of that dict. to run checks over it (and then e.g. call the DB)
  • Multiple times per second I'm updated a field of the value to one of the keys. (value is a struct) The same key will not be accessed concurrently.

Which locking strategy would you choose and why? My first shot is to use ReaderWriterLockSlim. But after I read it's a least two times slower than Monitor, I'm not so sure anymor开发者_C百科e, as everytime I access the dict, I'm going to lock very short.

tia Martin


Given that the most frequent operation is writing and you never need multiple concurrent readers as far as I can see, I would just use a normal lock. I can't see that ReaderWriterLockSlim would help you, and it will certainly give you more complex code.

EDIT: One possible optimization is to just access a list of changes from the writing threads. The reading thread would then need to lock that list just while it updates the underlying dictionary before processing it. Assuming the dictionary is very large but the list of changes is relatively small, that means the writing threads will be blocked for a lot less time.

In fact, you could use something like Queue instead of a list, and potentially make the reading thread dequeue small batches and yield, reducing the latency of the writing threads even further - so if there were 100 changes to process, the reading thread might read 10 of them, yield so that any writing threads blocked waiting to add to the queue could get their turn.

There are ever more complex solutions to this, depending on how critical the performance is, particularly in terms of latency - but I'd start off with just a lock round the dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜