title: Singleton instance using a Mutex
body: <p>I want to have a singleton class that can be shared across processes. So I naturally used the Mutex in .NET 4.0.</p>
  <p>Now I have two instances of the same application running. One modifies the &quot;Name&quot; property of this Singleton and all I want is the other application to pick up this change. But even after the first instance releases the Mutex, the second instance is not able to succeed in the WaitOne call. I wonder why and what I am doing wrong in the code below? Please note that the entry point is the method RunSingletonAcrossProcesses().</p>
  <h2>Here's my Singleton Class</h2>
  <pre><code>public class SingletonAcrossProcesses
  {
      
  private static SingletonAcrossProcesses _instance;
      
  private static Mutex _mutex = new Mutex(true, @&quot;Global\&quot; + &quot;sivablogz.wordpress.com SingletonMutexDemo&quot;);
  
      protected SingletonAcrossProcesses()
      {
      }
  
      public static SingletonAcrossProcesses GetInstance()
      {
          if (_mutex.WaitOne(TimeSpan.Zero, true))
          {
              if (_instance == null)
              {
                  _instance = new SingletonAcrossProcesses();
              }
              _mutex.ReleaseMutex();
          }            
          
          return _instance;                            
      }
  
      public string Name { get; set; }
  
      public static void RunSingletonAcrossProcesses()
      {
          Console.WriteLine(&quot;Press any key to Instantiate the singleton...&quot;);
          Console.ReadLine();
          SingletonAcrossProcesses instance = SingletonAcrossProcesses.GetInstance();
  
          if (instance != null)
          {
              if (String.IsNullOrEmpty(instance.Name))
              {
                  Console.WriteLine(&quot;Enter a name for the instance...&quot;);
                  instance.Name = Console.ReadLine();
              }
              Console.WriteLine(&quot;The Instance name is: &quot; + instance.Name);
          }
          else
              Console.WriteLine(&quot;The Singleton Instance could not be obtained.&quot;);            
          Console.WriteLine(&quot;Press any key to terminate...&quot;);
          Console.ReadLine();
      }
  }
  </code></pre>
  <p>Thanks in advance,</p>
  <p>Siva</p>