官术网_书友最值得收藏!

Using the Mutex construct

This recipe will describe how to synchronize two separate programs using the Mutex construct. A Mutex construct is a synchronization primitive that grants exclusive access of the shared resource to only one thread.

Getting ready

To step through this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter2\Recipe2.

How to do it...

To understand the synchronization of two separate programs using the Mutex construct, perform the following steps:

  1. Start Visual Studio 2015. Create a new C# console application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
    using static System.Console;
  3. Inside the Main method, add the following code snippet:
    const string MutexName = "CSharpThreadingCookbook";
    
    using (var m = new Mutex(false, MutexName))
    {
      if (!m.WaitOne(TimeSpan.FromSeconds(5), false))
      {
        WriteLine("Second instance is running!");
      }
      else
      {
        WriteLine("Running!");
        ReadLine();
        m.ReleaseMutex();
      }
    }
  4. Run the program.

How it works...

When the main program starts, it defines a mutex with a specific name, providing the initialOwner flag as false. This allows the program to acquire a mutex if it is already created. Then, if no mutex is acquired, the program simply displays Running and waits for any key to be pressed in order to release the mutex and exit.

If we start a second copy of the program, it will wait for 5 seconds, trying to acquire the mutex. If we press any key in the first copy of a program, the second one will start the execution. However, if we keep waiting for 5 seconds, the second copy of the program will fail to acquire the mutex.

Tip

Note that a mutex is a global operating system object! Always close the mutex properly; the best choice is to wrap a mutex object into a using block.

This makes it possible to synchronize threads in different programs, which could be useful in a large number of scenarios.

主站蜘蛛池模板: 桦川县| 昌都县| 墨江| 富顺县| 仙居县| 德保县| 商南县| 云林县| 普洱| 孟村| 哈巴河县| 绍兴县| 仙游县| 太湖县| 镶黄旗| 宁夏| 榆林市| 桓台县| 肥东县| 河津市| 白山市| 宜宾市| 广丰县| 泸溪县| 郴州市| 高碑店市| 交城县| 青岛市| 潜山县| 称多县| 丹棱县| 慈溪市| 黄大仙区| 林芝县| 乐清市| 应城市| 贵定县| 孙吴县| 临颍县| 贞丰县| 瓮安县|