1) Mutex: Synchronization between Processes (mutex).
2) Lock/monitor ... : Thread synchronization. Where lock is a simplified version of Monitor (directly generated Try{monitor.enter (...)} Finally{monitor.exit (...); Method.
Of course, monitor also has the Pulse method, which allows other threads to enter the prep zone while locking the same object, while cooperating with the Wait method (wait temporarily exits). In some cases, instead of the semaphore (ManualResetEvent), the following example is examined (source: http://bbs.csdn.net/topics/380095508):
classmymanualevent{Private ObjectLockobj =New Object(); Private BOOLHasset =false; Public voidSet () {Lock(lockobj)//queue up to get the key to unlock {Hasset=true; Monitor.pulseall (Lockobj); Notify the other queuing person to unlock the key first}} Public voidWaitOne () {Lock(lockobj)//queue up to pick up keys for unlocking while(!Hasset) {monitor.wait (lockobj); Wait for the notice to get the key unlocked} }}}classprogram{StaticMymanualevent mymanualevent =Newmymanualevent (); Static voidMain (string[] args) {ThreadPool.QueueUserWorkItem (Workerthread,"A"); ThreadPool.QueueUserWorkItem (Workerthread,"B"); Console.WriteLine ("press ENTER to signal the green light"); Console.ReadLine (); Mymanualevent.set (); ThreadPool.QueueUserWorkItem (Workerthread,"C"); Console.ReadLine (); } Static voidWorkerthread (ObjectState ) {Mymanualevent.waitone (); Console.WriteLine ("Thread {0} got the green light ...", state); }}
3) MethodImpl: is a feature that, under System.Runtime.CompilerServices, is equivalent to lock. When acting on a class method =lock (this), acting on a static method is equivalent to lock (typeof (a Class)).
4) Synchronizedattribute (under the System.Runtime.Remoting.Contexts namespace). Used for multiple program domains to instantiate a class so that the data and methods of the class can be synchronized (a single program domain is also available).
It is important to note that thesecond parameter of the Waithandler WaitOne method works here.
Example code:
namespaceconsoleapplication1{ [Synchronization ( true)] classMy:contextboundobject {Static voidMain (string[] args) {My My=NewMy (); ThreadPool.QueueUserWorkItem (My. Funca); ThreadPool.QueueUserWorkItem (My. Funca); Console.ReadLine (); } AutoResetEvent MyEvent=NewAutoResetEvent (false); Public voidFunca (ObjectState ) {Console.WriteLine ("Thread ID is:"+Thread.CurrentThread.ManagedThreadId); Myevent.waitone ( -,false);//To true you find that there will be a second thread that suddenly inserts and executesConsole.WriteLine ("======="); } }}
Differences in usage of Mutex,monitor,lock,methodimplattribute,synchronizedattribute