using System;
using System.Threading;
namespace Quasar.Client.Utilities
{
///
/// A user-wide mutex that ensures that only one instance runs at a time.
///
public class SingleInstanceMutex : IDisposable
{
///
/// The mutex used for process synchronization.
///
private readonly Mutex _appMutex;
///
/// Represents if the mutex was created on the system or it already existed.
///
public bool CreatedNew { get; }
///
/// Determines if the instance is disposed and should not be used anymore.
///
public bool IsDisposed { get; private set; }
///
/// Initializes a new instance of using the given mutex name.
///
/// The name of the mutex.
public SingleInstanceMutex(string name)
{
_appMutex = new Mutex(false, $"Local\\{name}", out var createdNew);
CreatedNew = createdNew;
}
///
/// Releases all resources used by this .
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Releases the mutex object.
///
/// True if called from , false if called from the finalizer.
protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
return;
if (disposing)
{
_appMutex?.Dispose();
}
IsDisposed = true;
}
}
}