Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of using examples of process synchronization Mutex Class in C #

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the "C# process synchronization Mutex class use case analysis", in the daily operation, I believe that many people have doubts in the C# process synchronization Mutex class use case analysis problem, the editor consulted all kinds of data, sorted out a simple and useful method of operation, hope to answer the "C# process synchronization Mutex class use case analysis" of the doubt to help! Next, please follow the editor to study!

Mutex is mutex in Chinese, and the Mutex class is called mutex. It can also be used for synchronization primitives for inter-process synchronization.

Mutex is similar to lock, but Mutex supports multiple processes. Mutex is about 20 times slower than lock.

Mutex (Mutex), a mechanism used in multithreading to prevent two threads from reading and writing to a common resource at the same time.

In Windows operating systems, Mutex synchronization objects have two states:

Signaled: not owned by any object

Nonsignaled: owned by a thread

Mutex can only release the lock in the thread that acquired it.

Constructors and methods

The constructor of the Mutex class is as follows:

The constructor states that Mutex () initializes a new instance of the Mutex class with the default property. Mutex (Boolean) initializes a new instance of the Mutex class with a Boolean value indicating whether the calling thread should have initial ownership of the mutex. Mutex (Boolean, String) initializes a new instance of the Mutex class with a Boolean value indicating whether the calling thread should have initial ownership of the mutex and whether the string is the name of the mutex. Mutex (Boolean, String, Boolean) initializes a new instance of the Mutex class with a Boolean value indicating whether the calling thread should have initial ownership of the mutex and whether the string is the name of the mutex and, when the thread returns, indicating whether the calling thread has been given initial ownership of the mutex.

Mutex is helpful for process synchronization, for example, the main application scenario is to control the system to run only one instance of this program.

The String type parameter in the Mutex constructor is called a mutex, which is a global operating system object.

Mutex will consume a lot of resources as long as it considers the synchronization between processes. Consider Monitor/lock in the process.

The common methods of Mutex are as follows:

The method states that Close () releases all resources occupied by the current WaitHandle. Dispose () releases all resources occupied by the current instance of the WaitHandle class. OpenExisting (String) opens the specified named mutex, if it already exists. ReleaseMutex () releases Mutex once. TryOpenExisting (String, Mutex) opens the specified named mutex (if it already exists) and returns a value indicating whether the operation was successful. WaitOne () blocks the current thread until the current WaitHandle receives a signal. WaitOne (Int32) blocks the current thread until the current WaitHandle receives the signal, while specifying the time interval in milliseconds using a 32-bit signed integer. WaitOne (Int32, Boolean) blocks the current thread until the current WaitHandle receives the signal, using a 32-bit signed integer to specify the time interval and whether to exit the synchronization domain before waiting. WaitOne (TimeSpan) blocks the current thread until the current instance receives a signal and uses TimeSpan to specify the time interval. WaitOne (TimeSpan, Boolean) blocks the current thread until the current instance receives the signal, using TimeSpan to specify the time interval and whether to exit the synchronization domain before waiting.

With regard to the Mutex class, we can first learn about it through a few examples.

The system can only run an instance of one program

The following is an example that controls that the system can run only one instance of this program and is not allowed to start multiple times at the same time.

Class Program {/ / the first program const string name = "www.whuanle.cn"; private static Mutex m; static void Main (string [] args) {/ / whether this program is the owner of Mutex bool firstInstance; m = new Mutex (false,name,out firstInstance) If (! firstInstance) {Console.WriteLine ("Program is already running! Press enter to exit!) ; Console.ReadKey (); return;} Console.WriteLine ("Program has started"); Console.WriteLine ("Press enter to exit"); Console.ReadKey (); m.ReleaseMutex (); m.Close (); return;}}

In the above code, there are some places not mentioned above, it doesn't matter, let's run the generated program first.

Explain the example above

How Mutex works:

When two or more threads access a shared resource at the same time, the operating system needs a synchronization mechanism to ensure that only one thread uses the resource at a time.

Mutex is a synchronization primitive, and Mutex grants exclusive access to shared resources to only one thread. This permission is based on the mutex, and when one thread acquires the mutex, other threads are suspended (blocked) until the first thread releases the mutex.

Corresponding to our previous code example, the constructor for instantiating the Mutex class is as follows:

M = new Mutex (false,name,out firstInstance)

The constructor prototype is as follows:

Public Mutex (bool initiallyOwned, string name, out bool createdNew)

As we mentioned earlier, Mutex objects have two states, signaled and nonsignaled.

Instantiating the Mutex class through new will check whether the mutex name has been used in the system, if not, the name mutex will be created and the thread has the right to use the mutex; at this point createdNew = = true.

So initiallyOwned, its role is to allow whether the thread can take initialization ownership of this mutex. Because we want only one program to run in the background, we want to set it to false.

About Mutex: https://docs.microsoft.com/zh-cn/windows-hardware/drivers/kernel/introduction-to-mutex-objects in driver Development

By the way, among the parameters of Mutex, name is very particular.

On a server running Terminal Services, the naming system mutex can have two levels of visibility.

If its name begins with the prefix "Global", mutex is visible in all Terminal Server sessions.

If its name begins with the prefix "Local", mutex is visible only in the Terminal Server session in which it was created. In this case, a separate mutex with the same name can exist in every other Terminal Server session on the server.

If no prefix is specified when creating a named mutex, the prefix "Local" is used. In a terminal server session, the names of two mutexes are only different in their prefixes, and they are visible to all processes in the terminal server session.

That is, the prefix names "Global" and "Local" describe the scope of the mutex name relative to the terminal server session, not to the process.

Please refer to:

Https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.mutex?view=netcore-3.1#methods

Https://www.yisu.com/article/237313.htm

Take over operation

To achieve this, when you click a program at the same time, only one instance A can run, and the other instances enter the waiting queue, wait for A to finish running, and then continue to run the next instance in the queue.

We compare each program to a person, simulating a toilet pit, where only one person can go to the toilet at a time, and others need to wait in line.

Use the WaitOne () method to wait for other processes to release mutexes, which is simulated queuing; the ReleaseMutex () method removes the occupation of the pit.

Class Program {/ / the first program const string name = "www.whuanle.cn"; private static Mutex m; static void Main (string [] args) {/ / wc has no location bool firstInstance; m = new Mutex (true,name,out firstInstance) / / someone is already on wc if (! firstInstance) {/ / waiting for the running instance to exit before this process can run. Console.WriteLine ("queue"); m.WaitOne (); GoWC (); return;} GoWC (); return;} private static void GoWC () {Console.WriteLine ("start wc"); Thread.Sleep (1000) Console.WriteLine (Open door); Thread.Sleep (1000); Console.WriteLine (closed door); Thread.Sleep (1000); Console.WriteLine (xxx); Thread.Sleep (1000); Console.WriteLine (Open door); Thread.Sleep (1000) Console.WriteLine ("leave wc"); m.ReleaseMutex (); Thread.Sleep (1000); Console.WriteLine ("wash hands");}}

At this point, we used the

M = new Mutex (true,name,out firstInstance)

After a program finishes, to allow other threads to create Mutex objects to get mutexes, you need to set the first parameter of the constructor to true.

You can also change it to false to see what anomalies will be reported.

You can use WaitOne (Int32) to set the waiting time (in milliseconds). If you don't queue up after this time, go to the bathroom somewhere else.

To avoid problems, consider performing m.ReleaseMutex () in the finally block.

Process synchronization example

Here we implement a scenario like this:

The parent process Parent starts the child process Children, waiting for the child process Children to finish executing, the child process exiting, and the parent process exiting.

Create a new .NET Core console project named Children with the following code in its Progarm

Using System;using System.Threading;namespace Children {class Program {const string name = "process synchronization example"; private static Mutex m; static void Main (string [] args) {Console.WriteLine ("child process is started..."); bool firstInstance; / / child process creates mutex m = new Mutex (true, name, out firstInstance) / according to the program we designed, create must be successful if (firstInstance) {Console.WriteLine ("sub-thread executes task"); DoWork (); Console.WriteLine ("sub-thread task completed"); / / release mutex m.ReleaseMutex () / / end program return;} else {Console.WriteLine ("inexplicable exception, exit directly");} private static void DoWork () {for (int I = 0; I)

< 5; i++) { Console.WriteLine("子线程工作中"); Thread.Sleep(TimeSpan.FromSeconds(1)); } } }} 然后发布或生成项目,打开程序文件位置,复制线程文件路径。 创建一个新项目,名为 Parent 的 .NET Core 控制台,其 Program 中的代码如下: using System;using System.Diagnostics;using System.Threading;namespace Parent{ class Program { const string name = "进程同步示例"; private static Mutex m; static void Main(string[] args) { // 晚一些再执行,我录屏要对正窗口位置 Thread.Sleep(TimeSpan.FromSeconds(3)); Console.WriteLine("父进程启动!"); new Thread(() =>

{/ / Promoter process Process process = new Process (); process.StartInfo.UseShellExecute = true; process.StartInfo.CreateNoWindow = false; process.StartInfo.WorkingDirectory = @ ".. / ConsoleApp9\ Children\ bin\ Debug\ netcoreapp3.1" Process.StartInfo.FileName = @ ".. / ConsoleApp9\ Children\ bin\ Debug\ netcoreapp3.1\ Children.exe"; process.Start (); process.WaitForExit ();}) .Start (); / / it takes some time for the child process to start Thread.Sleep (TimeSpan.FromSeconds (1)) / / get mutex bool firstInstance; m = new Mutex (true, name, out firstInstance); / / indicate that the child process is still running if (! firstInstance) {/ / wait for the end of the child process to run Console.WriteLine ("wait for the child process to finish running") M.WaitOne (); Console.WriteLine ("the child process ends and the program will exit automatically in 3 seconds"); m.ReleaseMutex (); Thread.Sleep (TimeSpan.FromSeconds (3)); return;}

Replace the program file path of the Children project with the part of the string in the Parent project promoter process.

Then start Parent.exe, and you can observe the running process of the following figure:

At this point, on the "C# process synchronization Mutex class use case analysis" study is over, I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report