1

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.

Community
  • 1
  • 1
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190

2 Answers2

3

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
  • 23,036
  • 8
  • 57
  • 80
1

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
  • 102,548
  • 21
  • 159
  • 201