Created
August 5, 2018 10:05
-
-
Save 13xforever/7748f857bb1333c6b95515dce65d5ba4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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