Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi instance restriction in c# windows application

Tags:

c#

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?

like image 354
user3548168 Avatar asked Apr 18 '14 08:04

user3548168


1 Answers

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();
        }


    }
}
like image 159
meziantou Avatar answered Oct 29 '22 13:10

meziantou