What synchronization primitives would you like to have in the .NET Framework?
The .NET framework currently offers several synchronization primitives:
- Monitors (via the Monitor class. C# users know this as the "lock" statement)
- Two varieties of reader/writer lock (ReaderWriterLock / ReaderWriterLockSlim)
- Events (ManualResetEvent/AutoResetEvent)
- Mutexes (for inter-process locking)
- Static constructors (which synchronize initialization of a class)
We also provide some basic building blocks for rolling your own synchronization mechanisms, via the Interlocked class, volatile variables, and Thread members like MemoryBarrier.
It's not uncommon to encounter a situation where the synchronization primitives we supply are not adequate. So all too often, people end up building their own (by far the most common case of this is the "double-checked locking" pattern). Building your own synchronization is time-consuming, and very difficult to get right. See my previous article for a simple example, or do a web search for double-checked locking.
I think there's clearly a need for some more specialized synchronization primitives in the Framework. Some ideas on my mind are:
- SpinLock (a super lightweight lock for very small critical sections)
- Some sort of lazy initialization primitive (see Joe Duffy's idea)
But I'd really like to hear from you. Have you found the existing primitives to be inadequate for your needs? Have you ever had to create your own? What could we add to the Framework to make your life easier?