Detailed. NET Synchronous and asynchronous mutexes

Source: Internet
Author: User
This essay continues:. NET synchronous and asynchronous thread-safe collections (11)

This essay and the next two essays will cover the last chunk of the. NET Synchronization and Asynchronous series: the WaitHandle family.

Abstract base class: WaitHandle, three sub-classes: EventWaitHandle (event notification), Mutex (Process sync Lock), Semaphone (semaphore), There are also two grandchildren: System.Threading.AutoResetEvent and System.Threading.ManualResetEvent, all of whom are eventwaithandle subclasses.

First, abstract base class WaitHandle

[ComVisibleAttribute (True)]public abstract class Waithandle:marshalbyrefobject, IDisposable

Through the above information, we can know that WaitHandle inherits from MarshalByRefObject, and implements the IDisposable interface.

For MarshalByRefObject, you may not be very familiar with it, but it's a lot of sub-classes you will certainly use, let us to uncover its truth.

In Msnd, this describes the MarshalByRefObject:

An application domain is a partition in which one or more applications reside in an operating system process. Communicate directly with objects in the same application domain. There are two ways to communicate objects in different application domains: one is to transfer copies of objects across application domain boundaries, and one is to use proxies to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by using proxies to exchange messages.

You may be more puzzled to see this, I used it? Have you ever used a subclass of it? Yes, it's just a subclass of it, and a lot more.

For example, the Brush, Image, Pen, Font, and so on in the System.Drawing namespace, as well as a stream under the System.IO namespace that you are more familiar with.

Extended reading: Using MarshalByRefObject to implement AOP.

See here we just need to know that WaitHandle has the ability to communicate across application domains.

Second, Mutex (process synchronization Lock)

1. MSDN defines a mutex as an inter-process synchronization primitive, the concept of a lock.

Monitor, which is used only to communicate between threads within an application domain. In fact, if the object used for the lock derives from Marshalbyrefobject,monitor, it can also provide locking in multiple application domains.

Mutexes are much more expensive to execute than Monitor because they need to invoke operating system resources, so if you only need to synchronize operations between threads within the application, Monitor/lock should be the preferred

2. Use of mutexes

  • WaitOne ()/waitone (TimeSpan, Boolean) and several overloads: request ownership, which is blocked until the current mutex receives a signal, or until an optional time-out interval is reached, none of these methods need to provide a locking object as an additional parameter.

      • You can use the WaitHandle.WaitOne method to request ownership of the mutex. The calling thread is blocked until one of the following conditions occurs:

      • The mutex sends a signal to indicate that it does not own. in this case, the WaitOne method returns true, calling the thread's mutex ownership, and accessing the resource protected by the mutex. after the thread finishes accessing the resource, you must call the ReleaseMutex method to release ownership of the mutex.

      • The timeout interval specified in the call WaitOne has a method of millisecondstimeout or the timeout parameter has elapsed. in this case, the WaitOne method returns false, at which point the thread does not acquire ownership of the mutex.

  • ReleaseMutex (): Releases the current Mutex once. Note that this is emphasized once, because the thread that owns the mutex can call the WaitOne series function repeatedly without preventing it from executing; the Enter ()/exit () of the monitor can be called repeatedly after acquiring the object lock. The number of times a mutex is invoked is saved by the common language runtime (CLR), and every WaitOne () counts +1 at a time, 1 per ReleaseMutex (), and as long as the count is not 0, the other mutex's waiting will assume that the mutex has not been released. There is no way to obtain the mutex. Also, as with Monitor.Exit (), only the owner of the mutex can Rleasemutex (), otherwise an exception is thrown.

  • If a thread terminates while owning a mutex, we call this mutex abandoned (abandoned). On MSDN, Microsoft warns that this is a "serious" programming error. This is to say that the owner of the mutex, after acquiring ownership, WaitOne () and Relasemutex () the wrong number of times, the caller itself is not responsible for the abort, causing the resource that the mutex is protecting may be in an inconsistent state. In fact, this is nothing more than reminding you to remember to use mutexes in the try/finally structure.

3 . Global and local mutexes

If you are using a mutex within an application domain, it would be better to use Monitor/lock directly, as the mutex previously mentioned requires a greater overhead and slower execution. However, the mutex is not monitor/lock after all, it is intended to be used for synchronization between processes. The mutex used for inter-process communication is called a global mutex and is used only for the mutex that communicates within the application domain, which we call a local mutex.

Global mutexes and local mutexes are constructed using constructors to construct different instances, let's look at the constructor of the mutex, a total of 5, pick two representative look at it:

    • Mutex (): a mutex obtained with a parameterless constructor has no name, and the process cannot share the data in the form of a variable, so a mutex without a name is also called a local (local) mutex. In addition, the creation of the mutex, the creator does not have ownership of this instance, still need to call WaitOne () to request ownership.

    • Mutex (Boolean initiallyowned, String name, out Booldan creatednew, mutexsecurity): first bool Parameter: Indicates whether the initialized instance has ownership of the mutex. The second string type, which specifies a name for the mutex, if string is null or an empty string is equivalent to creating a mutex without a name, when it belongs to a local mutex. A mutex with a name belongs to the global mutex. The third bool parameter, if the mutex has been initialized returns TRUE, returns False if the mutex already exists. The last parameter is used for security control of mutex access.

4. Use

A mutex is inherently a synchronization primitive between processes, so it can be used to control a single instance of an application :

///<summary>///Single Instance run///</summary>///<returns> True Application started, false no </returns>public bool Singlerun (ref System.Threading.Mutex mutex) {mutex = new System.threadin        G.mutex (False, "WINDOWS"); if (!mutex. WaitOne (0, false)) {mutex.        Close ();    Mutex = null;    } if (mutex = = null) {return true; } return false;} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.