Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in usage and implementation of ManualResetEvent(Slim), Semaphore(Slim) and ReaderWriterLock(Slim)

With .net 4.0 several new classes have been added relating to threading: ManualResetEventSlim, SemaphoreSlim and ReaderWriterLockSlim.

What is the difference between the Slim versions and the older classes, and when should I use one over the other?

like image 559
George Duckett Avatar asked Jul 20 '11 15:07

George Duckett


4 Answers

ReaderWriterLockSlim is a better version of ReaderWriterLock that is faster and doesn't suffer from writer starvation

ManualResetEventSlim and SemaphoreSlim are fully managed versions of a ManualResetEvent and Semaphore that spin-wait for a while before falling back to kernel objects, and so are faster than the old versions when wait times are short.

like image 159
Richard Blewett Avatar answered Nov 03 '22 07:11

Richard Blewett


I've made some illustrations to help me visualize the the sync primitives. Hope it helps someone else too.

SemaphoreSlim

enter image description here

CountdownEvent

enter image description here

Barrier

enter image description here

ManualResetEventSlim

enter image description here

like image 38
Niels Filter Avatar answered Nov 03 '22 09:11

Niels Filter


To quote directly from the documentation

"In the .NET Framework version 4, you can use the System.Threading.ManualResetEventSlim class for better performance when wait times are expected to be very short, and when the event does not cross a process boundary"

like image 8
Jamiec Avatar answered Nov 03 '22 07:11

Jamiec


ManualResetEventSlim and SemaphoreSlim are lighter versions of their kernel counterparts and don't allocate any kernel objects unless their WaitHandle property is called.

These types do not block directly when Wait is called, instead they spin briefly before blocking in case it got a signal

ManualResetEventSlim constructor can take SpinCount to customize the number of spns before blocking

Both these types support cancellation where you can pass a CancellationToken to the Wait method

SemaphoreSlim exposes a CurrentCount property where the Semaphore doesn't

ManualResetEventSlim has an IsSet property where ManualResetEvent doesn't.

like image 6
Emad Omara Avatar answered Nov 03 '22 09:11

Emad Omara