Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Security.AccessControl;
- using System.Security.Principal;
- using System.Threading;
- namespace WpfApplication13
- {
- public class SingleGlobalInstance : IDisposable
- {
- public bool hasHandle = false;
- Mutex mutex;
- void InitMutex(string mutexId)
- {
- if (string.IsNullOrWhiteSpace(mutexId))
- {
- string appGuid = ((AssemblyTitleAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false).GetValue(0)).Title.ToString();
- mutexId = string.Format("Global\\{{{0}}}", appGuid);
- }
- mutex = new Mutex(false, mutexId);
- var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
- var securitySettings = new MutexSecurity();
- securitySettings.AddAccessRule(allowEveryoneRule);
- mutex.SetAccessControl(securitySettings);
- }
- public SingleGlobalInstance(int timeOut, string mutexId = null)
- {
- InitMutex(mutexId);
- try
- {
- if (timeOut < 0)
- hasHandle = mutex.WaitOne(Timeout.Infinite, false);
- else
- hasHandle = mutex.WaitOne(timeOut, false);
- if (hasHandle == false)
- throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
- }
- catch (AbandonedMutexException)
- {
- hasHandle = true;
- }
- }
- public void Dispose()
- {
- if (mutex != null)
- {
- if (hasHandle)
- mutex.ReleaseMutex();
- mutex.Dispose();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment