Mutex, Monitor, lock, MethodImplAttribute, SynchronizedAttribute usage difference, synchronizedlock
1) Mutex: synchronization between processes (Mutex ).
2) lock/Monitor ...... : Thread synchronization. Here, lock is a simplified version of Monitor (directly generate try {Monitor. Enter (......)} Finally {Monitor. Exit (......);} Method.
Of course, there is also the Pulse method for Monitor,This method allows other threads to enter the preparation area when locking the same object, and works with the Wait method (Wait will temporarily quit). In some cases, you can replace the semaphores (ManualResetEvent) by examining the following example (Source: http://bbs.csdn.net/topics/380095508 ):
Class MyManualEvent {private object lockObj = new object (); private bool hasSet = false; public void Set () {lock (lockObj) // queue the key to be unlocked {hasSet = true; Monitor. pulseAll (lockObj); // notify other queuing persons to unlock the key first} public void WaitOne () {lock (lockObj) // queue the key for obtaining the unlock {while (! HasSet) {Monitor. wait (lockObj); // and other notifications, so that you can get the key to unlock }}} class Program {static MyManualEvent myManualEvent = new MyManualEvent (); static void Main (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 void WorkerThread (object state) {myManualEvent. waitOne (); Console. writeLine ("Thread {0} got the green light... ", state );}}
3) MethodImpl: a feature,In System. Runtime. CompilerServices, it 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) synchronizedattri (in the System. Runtime. Remoting. Contexts namespace ). UsedMultiple program DomainsInstantiate a class so that the data and methods of the class can be synchronized (a single program domain can also be ).
It is worth noting that:The second parameter of the WaitOne method of WaitHandler works here.
Sample Code:
Namespace ConsoleApplication1 {[Synchronization (True)]Class My:ContextBoundObject{Static void Main (string [] args) {My = new my (); ThreadPool. queueUserWorkItem (my. funcA); ThreadPool. queueUserWorkItem (my. funcA); Console. readLine ();} AutoResetEvent myEvent = new AutoResetEvent (false); public void FuncA (object state) {Console. writeLine ("Thread id is:" + Thread. currentThread. managedThreadId); myEvent. waitOne (2000, false); // if it is set to true, you will find a second thread suddenly inserted and executed the Console. writeLine ("====== ");}}}