dragonfly02
dragonfly02

Reputation: 3679

Use Semaphore to create a single instance application in C#

I am not sure why the code below won't enforce a single instance application on my work machine (Win7) but it works fine on my personal machine (Win8) at home (e.g. only one instance of the application can be run at a time). As far as I know each kernel handle object with the same name can only be created once. But I can run multiple instances of the application on my work machine...

static void Main(string[] args)
{
    bool createNew;
    const string appName = "TestMyApplication";
    using (new Semaphore(0, 1, appName, out createNew))
    {
        if (createNew)
        {
            Console.WriteLine("One instance of MyApplication is created and running...");
        }
        else
        {
            Console.WriteLine("Only one instance of MyApplication can be running at a time... Auto shut down in 3 seconds...");
            Thread.Sleep(3000);
        }
    }
   Console.ReadKey();
}

Upvotes: 2

Views: 1679

Answers (1)

TyCobb
TyCobb

Reputation: 9089

Your Console.ReadKey() is outside of the semaphore's scope. Your lock is getting destroyed instantly before your next application runs so it appears that both are running.

Below is the change that can be made to keep your 1st instance alive and still lock the other with an actual shut down.

using (new Semaphore(0, 1, appName, out createNew))
{
    if (createNew)
    {
        Console.WriteLine("One instance of MyApplication is created and running...");
        Console.ReadKey();
    }
    else
    {
        Console.WriteLine("Only one instance of MyApplication can be running at a time... Auto shut down in 3 seconds...");
        Thread.Sleep(3000);
        return;
    }
}

Upvotes: 4

Related Questions