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

Using the Mutex construct

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

Getting ready

To step through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe could be found at 7644_Code\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 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  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))
      {
        Console.WriteLine("Second instance is running!");
      }
      else
      {
        Console.WriteLine("Running!");
        Console.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 was acquired, the program simply displays Running, and waits for any key to be pressed 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 executing. However, if we keep waiting for 5 seconds, the second copy of the program will fail to acquire the mutex.

Tip

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

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

主站蜘蛛池模板: 怀远县| 合阳县| 平原县| 门头沟区| 花莲市| 东丽区| 夏津县| 富裕县| 伊金霍洛旗| 遂平县| 呼伦贝尔市| 乌苏市| 湘潭市| 正镶白旗| 吴旗县| 桂阳县| 辽中县| 杭锦后旗| 元阳县| 濉溪县| 阳信县| 商都县| 宾阳县| 平顺县| 府谷县| 盘山县| 麻城市| 财经| 盱眙县| 揭东县| 鹤庆县| 五大连池市| 建昌县| 乡宁县| 北海市| 宁远县| 贵港市| 珠海市| 仁怀市| 景洪市| 应城市|