protected void AquireMutex()
{
if (MachineWide)
{
var mutexSecurity = new MutexSecurity();
mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));
bool createdNew;
_mutex = new Mutex(false, @"Global\" + MutexName, out createdNew, mutexSecurity);
}
_mutex = new Mutex(false, MutexName);
try
{
switch (WaitHandle.WaitAny(new[] {_mutex, Handler.CancellationToken.WaitHandle},
millisecondsTimeout: (Handler.Verbosity == Verbosity.Batch) ? 30000 : 1000, exitContext: false))
{
case 0:
return;
case 1:
throw new OperationCanceledException();
default:
case WaitHandle.WaitTimeout:
throw new UnauthorizedAccessException("Another process is already holding the mutex " + MutexName + ".");
}
}
catch (AbandonedMutexException ex)
{
// Abandoned mutexes also get owned, but indicate something may have gone wrong elsewhere
Log.Warn(ex.Message);
}
}