What are various methods for thread synchronisation in c# [closed]
Apart from using lock(object) keyword, are there any fundamentally different or tricky or other useful in开发者_StackOverflow中文版 some situations ways to do syncronization ?
There are many classes in the Windows.Threading
namespace.
Monitor
and Mutex
being two important classes for synchronization within the namespace (there are others). Lock
is syntactic sugar for simple Monitor
operations.
Interlocked
provides some thread safe operations (Increment
, Decrement
and more).
I suggest going through the MSDN documentation for the namespace and different classed in it.
If you need to notify one thread of an event on a different thread, then ManualResetEvent
and AutoResetEvent
allow you to do so.
If you find that your code can handle simultaneous reads but need to synchronize writes, and your reading occurs much more frequently than your writes, then ReaderWriterLock
(or now ReaderWriterLockSlim
) will be of much help.
Mutex
and Semaphore
provide similar functionality to lock()
, but can be used to synchronize across processes.
There are some others, but those are the three main others I typically use.
The question is very broad.
There are books about different synchronization technics and which to use in which scenario.
There are a lot of different ways to do synchronization.
Overview of Synchronization Primitives
Quite a few of new synchronization primitives where added in .NET 4. http://msdn.microsoft.com/en-us/library/dd460718.aspx
精彩评论