using System; using System.Threading; namespace SyncEngine.Sync { public sealed class SyncInstanceLock : IDisposable { internal const string DefaultMutexName = @"Global\SyncCoordinator.SyncEngine"; private readonly Mutex _mutex; private bool _disposed; private SyncInstanceLock(Mutex mutex) { _mutex = mutex; } public static SyncInstanceLock TryAcquire() { return TryAcquire(DefaultMutexName); } internal static SyncInstanceLock TryAcquire(string mutexName) { Mutex mutex = null; try { mutex = new Mutex(initiallyOwned: true, mutexName, out var createdNew); if (!createdNew) { mutex.Dispose(); return null; } return new SyncInstanceLock(mutex); } catch (UnauthorizedAccessException) { mutex?.Dispose(); return null; } } public void Dispose() { if (_disposed) { return; } _disposed = true; try { _mutex.ReleaseMutex(); } catch (ApplicationException) { // Mutex not owned by this thread — ignore on shutdown. } _mutex.Dispose(); } } }