search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of .NET synchronization and asynchronous Mutex

This essay is continued: .NET synchronization and asynchronous thread-safe collection (11)

This essay and the next two essays will introduce the last major part of the .NET synchronization and asynchronous series. Block knowledge points: WaitHandle family.

Abstract base class: WaitHandle, three subclasses: EventWaitHandle (Event notification), Mutex (process synchronization lock), Semaphone (semaphore), and two grandchildren: System.Threading.AutoResetEvent, System. Threading.ManualResetEvent are all subclasses of EventWaitHandle.

1. 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.

You may not be very familiar with MarshalByRefObject, but you will definitely have used many of its subclasses. Let us reveal its true face.

MarshalByRefObject is described in MSND like this:

The application domain is a partition where one or more applications reside in an operating system process. Objects in the same application domain communicate directly. Objects in different application domains can communicate in two ways: by transferring copies of objects across application domain boundaries, or by using proxies to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using proxies.

You may be more confused after seeing this. Have I used it? Used its subclasses? That's right, its subclasses have been used, and there are many more.

For example, Brush, Image, Pen, Font, etc. in the System.Drawing namespace, and there is also a more familiar Stream under the System.IO namespace.

Extended reading: Utilization MarshalByRefObject Implements AOP.

Seeing this, we only need to know that WaitHandle has the ability to communicate across application domains.

2. Mutex (process synchronization lock)

1. MSDN defines Mutex as the synchronization primitive between processes, that is, the concept of lock.

On the other hand, Monitor is usually only used to communicate between threads in the application domain. In fact, Monitor can also provide locking in multiple application domains if the object used for the lock is derived from MarshalByRefObject.

Since Mutex needs to call operating system resources, its execution overhead is much greater than Monitor. Therefore, if you only need to synchronize operations between threads within the application, Monitor/lock should be the first choice

2. Usage of Mutex

  • WaitOne() /WaitOne(TimeSpan, Boolean) and several overloads: request ownership, this call will block until the current mutex receives a signal, or until When the optional timeout interval is reached, none of these methods need to provide a lock object as an additional parameter.

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

    • The mutex signals non-ownership. In this case, the WaitOne method will return true, , mutex ownership of the calling thread, and access to the resource protected by the mutex. After the thread completes accessing resources, the ReleaseMutex method must be called to release the ownership of the mutex.

    • ##Have methods millisecondsTimeout or ## for the timeout interval specified in the call to WaitOne #timeout The parameter has expired. In this case, the WaitOne method will return false, and the thread will not acquire ownership of the mutex at this time.

    ReleaseMutex(): Release the current Mutex once. Note that this is emphasized once, because the thread that owns the mutex can repeatedly call the WaitOne series of functions without blocking its execution; this and the Monitor's Enter()/Exit() can be called repeatedly after acquiring the object lock. Same. The number of times Mutex is called is saved by the common language runtime (CLR). The count is +1 for each WaitOne() and -1 for each ReleaseMutex(). As long as this count is not 0, other Mutex waiters will consider this Mutex If it is not released, there is no way to obtain the Mutex. In addition, like Monitor.Exit(), only the owner of the Mutex can RleaseMutex(), otherwise an exception will be thrown.
  • If the thread terminates while owning the mutex, we call the mutex abandoned. In MSDN, Microsoft warns that this is a "serious" programming error. This means that after the owner of the mutex obtains ownership, the number of WaitOne() and ReleaseMutex() is unequal, and the caller itself terminates irresponsibly, causing the resource being protected by the mutex to be in an inconsistent state. In fact, this is nothing more than a reminder to remember to use Mutex
  • in the try/finally structure.

3、全局和局部的Mutex

如果在一个应用程序域内使用Mutex,当然不如直接使用Monitor/lock更为合适,因为前面已经提到Mutex需要更大的开销而执行较慢。不过Mutex毕竟不是Monitor/lock,它生来应用的场景就应该是用于进程间同步的。用于在进程间通讯的Mutex我们称为全局Mutex,而只用于在应用程序域内部通讯的Mutex、我们称为局部Mutex.

全局Mutex和局部Mutex是通过构造函数来构造不同的实例的,让我们来看一下Mutex的构造函数,一共有5个,挑两个具有代表性的看一下吧:

  • Mutex():用无参数的构造函数得到的Mutex没有任何名称,而进程间无法通过变量的形式共享数据,所以没有名称的Mutex也叫做局部(Local)Mutex。另外,这样创建出的Mutex,创建者对这个实例并没有拥有权,仍然需要调用WaitOne()去请求所有权。

  • Mutex(Boolean initiallyOwned, String name, out Booldan createdNew, MutexSecurity):第一个bool参数:指示初始化的实例是否拥有互斥体所有权。第二个string类型、为互斥体指定一个名称,如果string为null或者空字符串 则相当于创建一个没有名字的Mutex,当属于局部Mutex. 而有名字的Mutex当属于全局Mutex.第三个bool参数、如果已经初始化了互斥体 返回True, 如果互斥体已经存在则返回False. 最后一个参数用于Mutex访问的安全性控制。

4、用途 

Mutex天生为进程间的同步基元,因此它可以用来控制应用程序的单实例

/// <summary>/// 单实例运行/// </summary>/// <returns> true 应用程序已启动,false 则没有 
</returns>public bool SingleRun(ref System.Threading.Mutex mutex )
{
    mutex = new System.Threading.Mutex(false, "WINDOWS");    
    if (!mutex.WaitOne(0, false))
    {
        mutex.Close();
        mutex = null;
    }    if (mutex == null)
    {        return true;
    }    return false;
}

The above is the detailed content of Detailed explanation of .NET synchronization and asynchronous Mutex. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software