Skip to content

Instantly share code, notes, and snippets.

@thejustinwalsh
Last active August 29, 2015 13:56
Show Gist options
  • Save thejustinwalsh/8981811 to your computer and use it in GitHub Desktop.
Save thejustinwalsh/8981811 to your computer and use it in GitHub Desktop.
Class to handle the case where you need a single instance of an application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/* Usage:
///////////////////////////////////////////////////////////////
static void Main (string[] args)
{
if (!SingleInstance.CreateInstance()) { return; }
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
SingleInstance.DestroyInstance();
}
*/
namespace App.Utils
{
static class SingleInstance
{
static private Mutex mutex;
static private string AssemblyGuid
{
get
{
object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
if (attributes.Length == 0)
{
return String.Empty;
}
return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value;
}
}
static public bool CreateInstance()
{
bool onlyInstance = false;
string mutexName = String.Format("Local\\{0}", SingleInstance.AssemblyGuid);
mutex = new Mutex(true, mutexName, out onlyInstance);
return onlyInstance;
}
static public void DestroyInstance()
{
mutex.ReleaseMutex();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment