andrew4582

SingleGlobalInstance Mutex

Jul 29th, 2014
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using System;
  2. using System.Reflection;
  3. using System.Runtime.InteropServices;
  4. using System.Security.AccessControl;
  5. using System.Security.Principal;
  6. using System.Threading;
  7.  
  8. namespace WpfApplication13
  9. {
  10.     public class SingleGlobalInstance : IDisposable
  11.     {
  12.         public bool hasHandle = false;
  13.         Mutex mutex;
  14.  
  15.         void InitMutex(string mutexId)
  16.         {
  17.             if (string.IsNullOrWhiteSpace(mutexId))
  18.             {
  19.                 string appGuid = ((AssemblyTitleAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false).GetValue(0)).Title.ToString();
  20.                 mutexId = string.Format("Global\\{{{0}}}", appGuid);
  21.             }
  22.            
  23.             mutex = new Mutex(false, mutexId);
  24.  
  25.             var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
  26.             var securitySettings = new MutexSecurity();
  27.             securitySettings.AddAccessRule(allowEveryoneRule);
  28.             mutex.SetAccessControl(securitySettings);
  29.         }
  30.  
  31.         public SingleGlobalInstance(int timeOut, string mutexId = null)
  32.         {
  33.             InitMutex(mutexId);
  34.             try
  35.             {
  36.                 if (timeOut < 0)
  37.                     hasHandle = mutex.WaitOne(Timeout.Infinite, false);
  38.                 else
  39.                     hasHandle = mutex.WaitOne(timeOut, false);
  40.  
  41.                 if (hasHandle == false)
  42.                     throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
  43.             }
  44.             catch (AbandonedMutexException)
  45.             {
  46.                 hasHandle = true;
  47.             }
  48.         }
  49.  
  50.         public void Dispose()
  51.         {
  52.             if (mutex != null)
  53.             {
  54.                 if (hasHandle)
  55.                     mutex.ReleaseMutex();
  56.                 mutex.Dispose();
  57.             }
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment