Skip to content

Instantly share code, notes, and snippets.

@kappa7194
Created April 6, 2018 10:04
Show Gist options
  • Save kappa7194/1265e55866c1c33b3b0cf821d5d1ce49 to your computer and use it in GitHub Desktop.
Save kappa7194/1265e55866c1c33b3b0cf821d5d1ce49 to your computer and use it in GitHub Desktop.
Single instance C# application
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
public static class Program
{
public static void Main()
{
var guidAttribute = Assembly.GetExecutingAssembly().GetCustomAttribute<GuidAttribute>();
var name = string.Format(CultureInfo.InvariantCulture, @"Global\{0}", guidAttribute.Value);
var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var mutexAccessRule = new MutexAccessRule(securityIdentifier, MutexRights.FullControl, AccessControlType.Allow);
var mutexSecurity = new MutexSecurity();
var hasHandle = false;
Mutex mutex = null;
mutexSecurity.AddAccessRule(mutexAccessRule);
try
{
mutex = new Mutex(false, name, out var isCreated, mutexSecurity);
if (isCreated)
{
// No other instances of the application are running.
Console.WriteLine("Mutex has been created.");
}
else
{
// There are other instances of the application running, they may or may not be doing work.
Console.WriteLine("Mutex already exists.");
}
try
{
hasHandle = mutex.WaitOne(TimeSpan.Zero, true);
}
catch (AbandonedMutexException)
{
hasHandle = true;
}
if (hasHandle)
{
// There are no other instances of the application doing work.
Console.WriteLine("Mutex has been acquired.");
}
else
{
// There is another instance of the application doing work.
Console.WriteLine("Mutex has not been acquired.");
}
Console.ReadKey(true);
}
finally
{
if (mutex != null)
{
if (hasHandle)
{
mutex.ReleaseMutex();
}
mutex.Dispose();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment