Skip to content

Instantly share code, notes, and snippets.

@13xforever
Created August 5, 2018 10:05
Show Gist options
  • Save 13xforever/7748f857bb1333c6b95515dce65d5ba4 to your computer and use it in GitHub Desktop.
Save 13xforever/7748f857bb1333c6b95515dce65d5ba4 to your computer and use it in GitHub Desktop.
internal static class Program
{
private static readonly SemaphoreSlim InstanceCheck = new SemaphoreSlim(0, 1);
private static readonly SemaphoreSlim ShutdownCheck = new SemaphoreSlim(0, 1);
internal static async Task Main(string[] args)
{
var thread = new Thread(() =>
{
using (var instanceLock = new Mutex(false, @"Global\mutex name"))
if (instanceLock.WaitOne(1000))
try
{
InstanceCheck.Release();
ShutdownCheck.Wait();
}
finally
{
instanceLock.ReleaseMutex();
}
});
try
{
thread.Start();
if (!InstanceCheck.Wait(1000))
{
Console.WriteLine("Another instance is already running.");
return;
}
// ...
}
finally
{
ShutdownCheck.Release();
thread.Join(100);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment