Multi-threaded programming Learning Series --- Mutex class

Code

static void Main()
{
	//定义一个互斥量
   const string MutextName = "CSharpThreadingCookbook";
   using (var m = new Mutex(false, MutextName))
   {
       if (!m.WaitOne(TimeSpan.FromSeconds(5), false))
       {
           Console.WriteLine("Second instance is running");
       }
       else
       {
           Console.WriteLine("Running");
           Console.ReadLine();
           m.ReleaseMutex();
       }
   }
   //此代码只为了方便截图,实际演示无用
   Console.ReadKey();
}

Running the first
Here Insert Picture Description
press any key in the first, second run within five seconds
Here Insert Picture Description
principles
startup defines a mutex, initialOwner set to false, meaning that if the mutex has been created, allowing the program to obtain the mutex, mutex if no response is received, the display running, wait until you press any key and then release the variables.
If we allow the same program, it will attempt to acquire the mutex within five seconds, if the first program at this time any key is pressed, the second program will begin execution. If, however, kept waiting for five seconds, the second program will not be able to get the mutex.

Note: The
mutex is a global operating system objects, be sure to properly close the mutex, preferably using a code block to wrap the mutex object.

This embodiment can be used to synchronize threads among different programs, it may be extended to a large number of usage scenarios.

Published 37 original articles · won praise 3 · Views 6332

Guess you like

Origin blog.csdn.net/huan13479195089/article/details/88884131