With .net 4.0 several new c开发者_开发技巧lasses 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?
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.
I've made some illustrations to help me visualize the the sync primitives. Hope it helps someone else too.
SemaphoreSlim
CountdownEvent
Barrier
ManualResetEventSlim
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"
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.
精彩评论