Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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