I have an application which uses INI files for start up. Multiple instances on of the same application with different INI files configuration.
This also results in multiple instances with same INI file can be started. I want to restrict only this case but multiple instance with different INI file must be allowed. what is the best way to achieve this?
Create a Mutex
with a name based on the ini file (MD5 of the file name or content). If the Mutex
already exists, it means the application is already started with the specified ini file.
public static string CalculateMD5Hash(string input)
{
using (MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
static void Main(string[] args)
{
using (Mutex mutex = new Mutex(true, CalculateMD5Hash(args[0])))
{
if (mutex.WaitOne(100))
{
Console.WriteLine("First instance");
Console.ReadKey();
}
else
{
Console.WriteLine("Second instance");
Console.ReadKey();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With