I’ve got a static variable (abstract data type, not a primitive) in my C# ASP.NET project.
It will be read by many threads, concurrently and frequently.
I need to write to it very rarely (compared to number of reads).
What is the best way of ensuring threadsaftey so that whilst im writing to it, other threads aren’t reading partially-written data?
I’ve only ever used lock, but i understand this will prevent concurrent reads 🙁
Thanks
I’d start off just with
lock. Uncontested locks are very cheap. You could useReaderWriterLockSlim(assuming you’re using .NET 3.5) but a lock is simpler to get right. Optimise it if/when it becomes a problem.Straight
ReaderWriterLockmay well be slower than the simple lock – it’s not as fast as it might be, hence the slim version 🙂Just how frequently do you mean by “frequently”? How much contention do you expect? You might want to model it (e.g. simulate a reasonable number of requests) and benchmark no locking vs simple locking, just to see what the overhead is.
You may be able to use the lock-free option of
volatile– but frankly I’ve recently given up on that as too hard for sane people to reason about. (It doesn’t mean what I thought it meant.)What are you actually doing with the data? Is the type an immutable type, so once you’ve got the right reference, you can read in a thread-safe way without any locking?