I have found possible slowdown in my app so I would have two questions:
- What is the real difference between simple locking on object and reader/writer locks?
E.g. I have a collection of clients, that change quickly. For iterations should I use readerlock or the simple lock is enough? - In order to decrease load, I have left iteration (only reading) of one collection without any locks. This collection changes often and quickly, but items are added and removed with writerlocks. Is it safe (I dont mind occassionally skipped item, this method runs in loop and its not critical) to left this reading unsecured by lock? I just dont want to have random exceptions.
No, your current scenario is not safe.
In particular, if a collection changes while you’re iterating over it, you’ll get an
InvalidOperationExceptionin the iterating thread. You should obtain a reader lock for the whole duration of your iterator:Note this is not the same as obtaining a reader lock for each step of the iteration – that won’t help.
As for the difference between reader/writer locks and “normal” locks – the idea of a reader/writer lock is that multiple threads can read at the same time, but only one thread can write (and only when no-one is reading). In some cases this can improve performance – but it increases the complexity of the solution too (in terms of getting it right). I’d also advise you to use
ReaderWriterLockSlimfrom .NET 3.5 if you possibly can – it’s much more efficient than the originalReaderWriterLock, and there are some inherent problems withReaderWriterLockIIRC.Personally I normally use simple locks until I’ve proved that lock contention is a performance bottleneck. Have you profiled your application yet to find out where the bottleneck is?