public static Mutex GrabMutex(string name) { var mutexName = "kalixLuceneSegmentMutex_" + name; try { return Mutex.OpenExisting(mutexName); } catch (WaitHandleCannotBeOpenedException) { var worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var security = new MutexSecurity(); var rule = new MutexAccessRule(worldSid, MutexRights.FullControl, AccessControlType.Allow); security.AddAccessRule(rule); var mutexIsNew = false; return new Mutex(false, mutexName, out mutexIsNew, security); } catch (UnauthorizedAccessException) { var m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions); var security = m.GetAccessControl(); var user = Environment.UserDomainName + "\\" + Environment.UserName; var rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); security.AddAccessRule(rule); m.SetAccessControl(security); return Mutex.OpenExisting(mutexName); } }
public UIMutex(string mutexName) { pGlobalMutexName = mutexName; // Create a string representing the current user. string userName = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. MutexSecurity mutexSecurity = new MutexSecurity(); // Add a rule that grants the current user the right // to enter or release the mutex. MutexAccessRule mutexAccessRule = new MutexAccessRule(userName, MutexRights.FullControl, AccessControlType.Allow); mutexSecurity.AddAccessRule(mutexAccessRule); bool createdNew = false; pMutex = new Mutex(false, pGlobalMutexName, out createdNew, mutexSecurity); if (createdNew) { // loggingSystem.LogVerbose("New Mutex created {0}", pGlobalMutexName); } else { //loggingSystem.LogVerbose("Existing Mutex opened {0}", globalMutextName); } }
protected override void OnStartup(StartupEventArgs e) { // store mutex result bool createdNew; // allow multiple users to run it, but only one per user var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // create mutex _instanceMutex = new Mutex(true, @"Global\MercurialForge_Mastery", out createdNew, securitySettings); // check if conflict if (!createdNew) { MessageBox.Show("Instance of Mastery is already running"); _instanceMutex = null; Application.Current.Shutdown(); return; } base.OnStartup(e); MainWindow window = new MainWindow(); MainWindowViewModel viewModel = new MainWindowViewModel(window); window.DataContext = viewModel; window.Show(); }
public InterProcessMutexLock(String mutexName) { try { _mutexName = mutexName; try { _currentMutex = Mutex.OpenExisting(_mutexName); } catch (WaitHandleCannotBeOpenedException) { // grant everyone access to the mutex var security = new MutexSecurity(); var everyoneIdentity = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new MutexAccessRule(everyoneIdentity, MutexRights.FullControl, AccessControlType.Allow); security.AddAccessRule(rule); // make sure to not initially own it, because if you do it also acquires the lock // we want to explicitly attempt to acquire the lock ourselves so we know how many times // this object acquired and released the lock _currentMutex = new Mutex(false, mutexName, out _created, security); } AquireMutex(); } catch(Exception ex) { var exceptionString = String.Format("Exception in InterProcessMutexLock, mutex name {0}", mutexName); Log.Error(this, exceptionString, ex); throw ExceptionUtil.Rethrow(ex, exceptionString); } }
// Note: configuration based on stackoverflow answer: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c public BankAccountMutex(double money) { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; // set up security for multi-user usage // work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex = new Mutex(false, mutexId, out createdNew, securitySettings); LogConsole("Setting initial amount of money: " + money); if (money < 0) { LogConsole("The entered money quantity cannot be negative. Money: " + money); throw new ArgumentException(GetMessageWithTreadId("The entered money quantity cannot be negative. Money: " + money)); } this.bankMoney = money; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(true); string title = "KeyMagic"; bool beta = Properties.Settings.Default.BetaRelease; if (beta) title += " (beta)"; string mutexName = "\u1000\u1001"; // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 using (var mutex = new Mutex(false, mutexName)) { // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); //edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever //edited by acidzombie24 //mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(100, false); if (hasHandle == false) //another instance exist { IntPtr pWnd = NativeMethods.FindWindow(null, title); if (pWnd != IntPtr.Zero) { NativeMethods.ShowWindow(pWnd, 0x05); } return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired } frmMain f = new frmMain(); Application.Run(); } finally { //edit by acidzombie24, added if statemnet if (hasHandle) mutex.ReleaseMutex(); } } }
public static Mutex CreateMutexWithFullControlRights(String name, out Boolean createdNew) { SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null); MutexSecurity mutexSecurity = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(securityIdentifier, MutexRights.FullControl, AccessControlType.Allow); mutexSecurity.AddAccessRule(rule); return new Mutex(false, name, out createdNew, mutexSecurity); }
// Methods public MutexHelper(string mutexName) { bool flag; this.pGlobalMutexName = mutexName; string identity = Environment.UserDomainName + @"\" + Environment.UserName; MutexSecurity mutexSecurity = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow); mutexSecurity.AddAccessRule(rule); this.pMutex = new Mutex(false, this.pGlobalMutexName, out flag, mutexSecurity); }
private void InitMutex(Guid appGuid) { var 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 static MutexSecurity MutexSecurity() { SecurityIdentifier user = GetEveryoneSID(); MutexSecurity result = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify | MutexRights.Delete, AccessControlType.Allow); result.AddAccessRule(rule); return result; }
private void InitMutex() { var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value; var 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); }
private static Mutex BuildMutex(string name) { name = name.Replace(":", "_"); name = name.Replace("/", "_"); name = name.Replace("\\", "_"); string mutexId = string.Format("Global\\{0}", name); var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); bool createdNew; var mutex = new Mutex(false, mutexId, out createdNew, securitySettings); return mutex; }
/// <summary> /// Creates a global mutex and allows everyone access to it. /// </summary> /// <param name="name">The name of the mutex to create in the Global namespace.</param> public GlobalMutex(string name) { // Allow full control of the mutex for everyone so that other users will be able to // create the same mutex and synchronise on it, if required. var allowEveryoneRule = new MutexAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); bool createdNew; // Use the Global prefix to make it a system-wide object mutex = new Mutex(false, @"Global\" + name, out createdNew, securitySettings); }
private void InitWaitHandle() { string mutexId = String.Format("Global\\{{{0}}}", _key); try { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); bool wasCreated = false; _waitHandle = new Mutex(false, mutexId, out wasCreated, securitySettings); } catch (Exception) { // We fallback to AutoResetEvent because Mutex isn't supported in medium trust. _waitHandle = _namedLocks.GetOrAdd(_key, key => new AutoResetEvent(true)); } }
public static bool TryGetMutex() { //source: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c // get application GUID as defined in AssemblyInfo.cs //string appGuid = "SjUpdater\\v" +Assembly.GetExecutingAssembly().GetName().Version.Major; string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); mutex = new Mutex(false, mutexId); // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); // edited by acidzombie24 try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) throw new TimeoutException("Timeout waiting for exclusive access"); } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } return true; } catch { return false; } }
static void Main(string[] args) { string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); string mutexId = string.Format("Global\\{{{0}}}", appGuid); using (var 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); // edited by acidzombie24 var hasHandle = false; try { try { hasHandle = mutex.WaitOne(2000, false); if (hasHandle == false) { MessageBox.Show("osu!StreamCompanion is already running.", "Error"); return; } } catch (AbandonedMutexException) { hasHandle = true; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); _initializer = new Initializer(); _initializer.Start(); Application.Run(_initializer); } finally { if (hasHandle) mutex.ReleaseMutex(); } } }
protected override void OnStart(string[] args) { base.OnStart(args); client = new WlanClient(); //Miofile = "C:\\" + DateTime.Now.ToLongDateString() + "-" +DateTime.Now.ToShortTimeString() + "_catture.txt"; //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n"); // Initialize data structure aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = default_interval; //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n"); //initialize the mutex mut = new Mutex(false,"Global\\ServiceMutex"); MutexSecurity mSec = mut.GetAccessControl(); var rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Modify | MutexRights.Synchronize | MutexRights.TakeOwnership | MutexRights.ReadPermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); mut.SetAccessControl(mSec); // Set the time interval //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n"); // File Mapping creation try { mmf = MemoryMappedFile.CreateNew("Global\\Broadcast", MappedFileDimension, MemoryMappedFileAccess.ReadWrite); } catch (Exception e) { System.IO.File.AppendAllText("c:\\catture.txt", e.ToString()); } var mmfSec = mmf.GetAccessControl(); mmfSec.SetAccessRule(new AccessRule<MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null),MemoryMappedFileRights.FullControl | MemoryMappedFileRights.Read, AccessControlType.Allow)); mmf.SetAccessControl(mmfSec); //System.IO.File.AppendAllText("c:\\catture.txt", "PARTOOOOOOOOOOOOOOOOOOOOO\r\n"); stream = mmf.CreateViewStream(0, MappedFileDimension, MemoryMappedFileAccess.ReadWrite); //System.IO.File.AppendAllText("c:\\catture.txt", "FINISCO PARTENZA\r\n"); aTimer.Enabled = true; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Initialize variables for mutex. string MutexId = string.Format("Global\\{{{0}}}", Guid); bool CreatedNewMutex; MutexAccessRule AllowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity SecuritySettings = new MutexSecurity(); SecuritySettings.AddAccessRule(AllowEveryoneRule); using (Mutex Mutex = new Mutex(false, MutexId, out CreatedNewMutex, SecuritySettings)) { bool HandleAcquired = false; try { try { HandleAcquired = Mutex.WaitOne(2000, false); if (!HandleAcquired) { MessageBox.Show("There is an instance of " + Name + " already currently running.", Name + " already open.", MessageBoxButtons.OK, MessageBoxIcon.Information); Close(); } } catch (AbandonedMutexException) { // The mutex was abandoned in another process, so in this case it will still get acquired. HandleAcquired = true; } // Begin program. Application.Run(new MainForm()); // End program. } finally { // Release the mutex if it was acquired. if (HandleAcquired) Mutex.ReleaseMutex(); } } }
public ManagedFileLock(string name) { _name = name; var mutexName = String.Format(@"Global\{0}", name); if (!FileExtensions.TryOpenExistingMutex(mutexName, out _mutex)); { bool isNew = true; MutexSecurity mSec = new MutexSecurity(); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); MutexAccessRule rule = new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow); mSec.AddAccessRule(rule); _mutex = new Mutex(false, mutexName, out isNew, mSec); } if (!_mutex.WaitOne(10000)) throw new InvalidOperationException(string.Format("File Locked {0}", _name)); }
public static Mutex Create(string Name, out bool mutexWasCreated) { //Always use global scop string name = @"Global\" + Name; MutexSecurity sec = new MutexSecurity(); MutexAccessRule secRule = new MutexAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); sec.AddAccessRule(secRule); bool mutexWasCreatedOut; Mutex m = new Mutex(false, name, out mutexWasCreatedOut, sec); mutexWasCreated = mutexWasCreatedOut; return m; }
private SingleInstanceApp() { _id = "SIA_" + GetAppId(); //string identity = "Everyone"; string identity = Environment.UserDomainName + "\\" + Environment.UserName; MutexAccessRule rule = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow); MutexSecurity security = new MutexSecurity(); try { security.AddAccessRule(rule); _instanceCounter = new Mutex(false, _id, out _firstInstance, security); } catch { _firstInstance = true; } }
public void CanSetAndGetMutexSecurity () { if (PlatformID.Win32NT != Environment.OSVersion.Platform) { Assert.Ignore (); return; } MutexAccessRule rule; SecurityIdentifier sid; AuthorizationRuleCollection rulesA, rulesB, rulesC; bool createdNew; MutexSecurity security; string name = @"Local\MonoTestMutex"; using (Mutex mutex = new Mutex(false, name, out createdNew)) { Assert.IsTrue (createdNew); security = mutex.GetAccessControl (); rulesA = security.GetAccessRules (true, false, typeof (SecurityIdentifier)); Assert.AreNotEqual (0, rulesA.Count); // Contrary to what you'd expect, these classes only try to persist sections that // that were *changed*. Awful, eh? To be fair, if you retrieve and modify it's fine. security = new MutexSecurity (); mutex.SetAccessControl (security); security = mutex.GetAccessControl (); rulesB = security.GetAccessRules (true, false, typeof (SecurityIdentifier)); Assert.AreEqual (rulesA.Count, rulesB.Count); // And here's our dummy change. Observe... sid = new SecurityIdentifier( "S-1-5-12-3456-7890"); rule = new MutexAccessRule (sid, MutexRights.Synchronize, AccessControlType.Allow); security = new MutexSecurity (); security.RemoveAccessRuleSpecific (rule); mutex.SetAccessControl (security); security = mutex.GetAccessControl (); rulesC = security.GetAccessRules (true, false, typeof (SecurityIdentifier)); Assert.AreEqual (0, rulesC.Count); } }
public static Mutex GrabMutex(string name) { var mutexName = "luceneSegmentMutex_" + name; Mutex mutex; var notExisting = false; if (Mutex.TryOpenExisting(mutexName, MutexRights.Synchronize | MutexRights.Modify, out mutex)) { return mutex; } // Here we know the mutex either doesn't exist or we don't have the necessary permissions. if (!Mutex.TryOpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions, out mutex)) { notExisting = true; } if (notExisting) { var worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var security = new MutexSecurity(); var rule = new MutexAccessRule(worldSid, MutexRights.FullControl, AccessControlType.Allow); security.AddAccessRule(rule); var mutexIsNew = false; return new Mutex(false, mutexName, out mutexIsNew, security); } else { var m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions); var security = m.GetAccessControl(); var user = Environment.UserDomainName + "\\" + Environment.UserName; var rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); security.AddAccessRule(rule); m.SetAccessControl(security); return Mutex.OpenExisting(mutexName); } }
public void CreateMutex(int timeOut = 100) { // Получаем GUID и формируем имя мутекса string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); string 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); try { // Попытка получить эксклюзивный доступ к мутексу с таким именем (если не получится, значит нас опередили) Success = mutex.WaitOne(timeOut, false); } catch (AbandonedMutexException) { // "Брошенный" мутекс (видимо завершили задачу в "Диспетчер задач") Success = true; } }
protected GatewayBase(string mutexName, Guid uniqueIdentifier, int timeout, string customError, bool doNotAutoEnter) { if (string.IsNullOrWhiteSpace(mutexName)) throw new ArgumentException("mutexName cannot be empty"); if (uniqueIdentifier == Guid.Empty) throw new ArgumentException("uniqueIdentifier cannot be empty"); MutexName = mutexName; UniqueIdentifier = uniqueIdentifier.ToString().ToUpperInvariant(); UniqueId = MutexName + UniqueIdentifier; mutexId = string.Format("Global\\{{{0}}}", UniqueId); 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); if (!doNotAutoEnter) { Enter(timeout, customError); } }
/// <summary> /// Executes the task. /// </summary> protected override void ExecuteTask() { if (this.MutexName.StartsWith("Global\\")) throw new BuildException("Do not prefix the mutex ID with \"Global\\\". A global mutex is obtained by setting the property \"global\" to \"true\" (which is the default)."); // A global mutex requires the prefix "Global\\" string mname = !this.Global ? this.MutexName : string.Format("Global\\{0}", this.MutexName); var mutex = new Mutex(false, mname); // A true global mutex needs some security settings if (this.Global) { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); } try { if (!mutex.WaitOne(this.Timeout)) throw new BuildException("Timeout waiting on mutex \"" + mname + "\"."); } catch (AbandonedMutexException) { this.Log(Level.Warning, "A previous process abandoned mutex \"{0}\"", mname); } try { this.ExecuteChildTasks(); } finally { mutex.ReleaseMutex(); } }
public GlobalReaderWriterLock(string nameOfThisLock) { _hatName = nameOfThisLock; // we need to make two native sync objects, a mutex and a semaphore // that are global so every process and user on the system can share them as long as they agree on the lock's name string mutexId = string.Format("Global\\Mut_{0}", _hatName); string semaphoreId = string.Format("Global\\Sem_{0}", _hatName); bool iDontCareWhetherItsNew; { MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); _holdTheHat = new Mutex(false, mutexId, out iDontCareWhetherItsNew, securitySettings); } { SemaphoreAccessRule allowEveryoneRule = new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow); SemaphoreSecurity securitySettings = new SemaphoreSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); _chipsInTheHat = new Semaphore(READER_CHIPS, READER_CHIPS, semaphoreId, out iDontCareWhetherItsNew, securitySettings); } }
/// <summary> /// Check if an application is running or not /// </summary> /// <returns>returns true if already running</returns> public static bool IsAlreadyRunning(string MUTEX_ID, out Mutex mutex) { // Allow only one instance mutex = new Mutex(false, MUTEX_ID); var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); bool hasHandle = false; try { // Check if we can start the application hasHandle = mutex.WaitOne(500, false); } catch (AbandonedMutexException) { // The mutex was abandoned in another process, it will still get aquired hasHandle = true; } return !hasHandle; }
/// <summary>搜索与指定的规则具有相同用户和 <see cref="T:System.Security.AccessControl.AccessControlType" />(允许或拒绝)的所有访问控制规则,如果找到则将其移除。</summary> /// <param name="rule">一个 <see cref="T:System.Security.AccessControl.MutexAccessRule" />,指定要搜索的用户和 <see cref="T:System.Security.AccessControl.AccessControlType" />。此规则指定的任何权限都被忽略。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="rule" /> 为 null。</exception> public void RemoveAccessRuleAll(MutexAccessRule rule) { this.RemoveAccessRuleAll((AccessRule)rule); }
/// <summary>搜索与指定的规则完全匹配的访问控制规则,如果找到则将其移除。</summary> /// <param name="rule">要移除的 <see cref="T:System.Security.AccessControl.MutexAccessRule" />。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="rule" /> 为 null。</exception> public void RemoveAccessRuleSpecific(MutexAccessRule rule) { this.RemoveAccessRuleSpecific((AccessRule)rule); }
public bool RemoveAccessRule(MutexAccessRule rule) { return(base.RemoveAccessRule(rule)); }
/// <summary>搜索可以将新规则与之合并的匹配访问控制规则。如果未找到符合条件的规则,则添加新规则。</summary> /// <param name="rule">要添加的访问控制规则。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="rule" /> 为 null。</exception> /// <exception cref="T:System.Security.Principal.IdentityNotMappedException"> /// <paramref name="rule " /> 无法映射到已知标识。</exception> public void AddAccessRule(MutexAccessRule rule) { this.AddAccessRule((AccessRule)rule); }
public bool RemoveAccessRule(MutexAccessRule rule) { throw new NotImplementedException(); }
/// <summary>移除与指定的规则具有相同用户和 <see cref="T:System.Security.AccessControl.AccessControlType" />(允许或拒绝)的所有控制规则,然后添加指定的规则。</summary> /// <param name="rule">要相加的 <see cref="T:System.Security.AccessControl.MutexAccessRule" />。由此规则的用户和 <see cref="T:System.Security.AccessControl.AccessControlType" /> 确定在添加此规则之前要移除的规则。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="rule" /> 为 null。</exception> public void SetAccessRule(MutexAccessRule rule) { this.SetAccessRule((AccessRule)rule); }
public void AddAccessRule(MutexAccessRule rule) { }
public void AddAccessRule(MutexAccessRule rule) { base.AddAccessRule(rule); }
public void RemoveAccessRuleSpecific(MutexAccessRule rule) { base.RemoveAccessRuleSpecific(rule); }
public void RemoveAccessRuleAll(MutexAccessRule rule) { base.RemoveAccessRuleAll(rule); }
/// <summary>搜索如下的访问控制规则:与指定的访问规则具有相同的用户和 <see cref="T:System.Security.AccessControl.AccessControlType" />(允许或拒绝),并具有兼容的继承和传播标志;如果找到,则从中移除指定访问规则中包含的权限。</summary> /// <returns>如果找到一个兼容规则,则为 true;否则为 false。</returns> /// <param name="rule">指定要搜索的用户和 <see cref="T:System.Security.AccessControl.AccessControlType" /> 的 <see cref="T:System.Security.AccessControl.MutexAccessRule" />,以及匹配规则(如果找到)必须兼容的一组继承和传播标志。指定要从兼容规则移除的权限(如果找到)。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="rule" /> 为 null。</exception> public bool RemoveAccessRule(MutexAccessRule rule) { return(this.RemoveAccessRule((AccessRule)rule)); }
public bool RemoveAccessRule(MutexAccessRule rule) { return(default(bool)); }
/// <summary>不论 <see cref="T:System.Security.AccessControl.AccessControlType" /> 如何,移除与指定的规则具有相同用户的所有访问控制规则,然后添加指定的规则。</summary> /// <param name="rule">要相加的 <see cref="T:System.Security.AccessControl.MutexAccessRule" />。由此规则指定的用户确定在添加此规则之前要移除的规则。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="rule" /> 为 null。</exception> public void ResetAccessRule(MutexAccessRule rule) { this.ResetAccessRule((AccessRule)rule); }
public void RemoveAccessRuleAll(MutexAccessRule rule) { }
public void AddAccessRule(MutexAccessRule rule) { throw new NotImplementedException(); }
public void RemoveAccessRuleSpecific(MutexAccessRule rule) { }
public void RemoveAccessRuleSpecific(MutexAccessRule rule) { throw new NotImplementedException(); }
public void ResetAccessRule(MutexAccessRule rule) { }
public void SetAccessRule(MutexAccessRule rule) { base.SetAccessRule(rule); }
public void Launch(AddInHost host) { // uncomment to debug #if DEBUG host.MediaCenterEnvironment.Dialog("Attach debugger and hit ok", "debug", DialogButtons.Ok, 100, true); #endif using (Mutex mutex = new Mutex(false, Kernel.MBCLIENT_MUTEX_ID)) { //set up so everyone can access var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); try { //don't bomb if this fails securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); } catch (Exception) { //we don't want to die here and we don't have a logger yet so just go on } try { if (mutex.WaitOne(100,false)) { var config = GetConfig(); if (config == null) { Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } Environment.CurrentDirectory = ApplicationPaths.AppConfigPath; try { CustomResourceManager.SetupStylesMcml(host); CustomResourceManager.SetupFontsMcml(host); } catch (Exception ex) { host.MediaCenterEnvironment.Dialog(ex.Message, Application.CurrentInstance.StringData("CustomErrorDial"), DialogButtons.Ok, 100, true); Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } using (new MediaBrowser.Util.Profiler("Total Kernel Init")) { Kernel.Init(config); } using (new MediaBrowser.Util.Profiler("Application Init")) { Application app = new Application(new MyHistoryOrientedPageSession(), host); app.GoToMenu(); } mutex.ReleaseMutex(); } else { //another instance running and in initialization - just blow out of here Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get acquired Logger.ReportWarning("Previous instance of core ended abnormally..."); mutex.ReleaseMutex(); } } }
private static string GetModulePath() { // UI thread... if (modulePath == null) { // Extract the embedded SciLexer DLL // http://stackoverflow.com/a/768429/2073621 var version = typeof(Scintilla).Assembly.GetName().Version.ToString(3); modulePath = Path.Combine(Path.GetTempPath(), "ScintillaNET", version, (IntPtr.Size == 4 ? "x86" : "x64"), "SciLexer.dll"); if (!File.Exists(modulePath)) { // http://stackoverflow.com/a/229567/2073621 // Synchronize access to the file across processes var guid = ((GuidAttribute)typeof(Scintilla).Assembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); var name = string.Format(CultureInfo.InvariantCulture, "Global\\{{{0}}}", guid); using (var mutex = new Mutex(false, name)) { var access = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var security = new MutexSecurity(); security.AddAccessRule(access); mutex.SetAccessControl(security); var ownsHandle = false; try { try { ownsHandle = mutex.WaitOne(5000, false); // 5 sec if (ownsHandle == false) { var timeoutMessage = string.Format(CultureInfo.InvariantCulture, "Timeout waiting for exclusive access to '{0}'.", modulePath); throw new TimeoutException(timeoutMessage); } } catch (AbandonedMutexException) { // Previous process terminated abnormally ownsHandle = true; } // Double-checked (process) lock if (!File.Exists(modulePath)) { // Write the embedded file to disk var directory = Path.GetDirectoryName(modulePath); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); var resource = string.Format(CultureInfo.InvariantCulture, "ScintillaNET.{0}.SciLexer.dll.gz", (IntPtr.Size == 4 ? "x86" : "x64")); using (var resourceStream = typeof(Scintilla).Assembly.GetManifestResourceStream(resource)) using (var gzipStream = new GZipStream(resourceStream, CompressionMode.Decompress)) using (var fileStream = File.Create(modulePath)) gzipStream.CopyTo(fileStream); } } finally { if (ownsHandle) mutex.ReleaseMutex(); } } } } return modulePath; }
public void ResetAccessRule(MutexAccessRule rule) { base.ResetAccessRule(rule); }