views:

137

answers:

2

Possible duplicate: Run single instance of an application using Mutex

I am using VS 2008 in C# on a console application. Not sure if there is any class available (process?) to limit only single console application running at a time.

+3  A: 

There is no such class, but you can use System.Threading.Mutex to build one.

Mutex is a synchronization primitive that can also be used for interprocess synchronization.

See example: How ensure that only one instance of an application will run?

Rinat Abdullin
+1  A: 

I quickly slapped this together, but it does show the second console briefly and then hides it. Not sure if there's a way to block the second console from even showing up...

class Program
{
    private static Mutex mutex;

    static void Main(string[] args)
    {
        mutex = new Mutex(true, "MyMutex");
        if (!mutex.WaitOne(0, false))
        {
            return;
        }
        Console.WriteLine("Application started");
        Console.ReadKey(true);

    }
}

You'll need to add a reference to System.Threading.

BFree