Using C# and WPF under .NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance?
I kno
Well, I have a disposable Class for this that works easily for most use cases:
Use it like this:
static void Main()
{
using (SingleInstanceMutex sim = new SingleInstanceMutex())
{
if (sim.IsOtherInstanceRunning)
{
Application.Exit();
}
// Initialize program here.
}
}
Here it is:
///
/// Represents a class.
///
public partial class SingleInstanceMutex : IDisposable
{
#region Fields
///
/// Indicator whether another instance of this application is running or not.
///
private bool isNoOtherInstanceRunning;
///
/// The used to ask for other instances of this application.
///
private Mutex singleInstanceMutex = null;
///
/// An indicator whether this object is beeing actively disposed or not.
///
private bool disposed;
#endregion
#region Constructor
///
/// Initializes a new instance of the class.
///
public SingleInstanceMutex()
{
this.singleInstanceMutex = new Mutex(true, Assembly.GetCallingAssembly().FullName, out this.isNoOtherInstanceRunning);
}
#endregion
#region Properties
///
/// Gets an indicator whether another instance of the application is running or not.
///
public bool IsOtherInstanceRunning
{
get
{
return !this.isNoOtherInstanceRunning;
}
}
#endregion
#region Methods
///
/// Closes the .
///
public void Close()
{
this.ThrowIfDisposed();
this.singleInstanceMutex.Close();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
/* Release unmanaged ressources */
if (disposing)
{
/* Release managed ressources */
this.Close();
}
this.disposed = true;
}
}
///
/// Throws an exception if something is tried to be done with an already disposed object.
///
///
/// All public methods of the class must first call this.
///
public void ThrowIfDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
}
#endregion
}