March, 2010


5
Mar 10

Single instance .NET executables

It’s not a common problem, which probably explains why there isn’t much information out there on the topic, but how do you make it so that your executable can only have a single running instance? That is, if you user tries to launch the same programme twice, the second instance silently closes down.

There aren’t many obvious practical uses for this, but they are out there and they do exist. We’ve come across the requirement a few times as consultants to enterprise organisations — for example, a utility that gathers information on a wire that must only be running a single instance — and it took us a while before we settled on the code to solve it.

We tried various methods — broadcasting on sockets, named pipes, magic ‘lock’ files (this is the simplest solution, and the one that a lot of software uses — it’s effectively a file with a non-sharable lock — if you can’t lock the file, the app is already running). We finally came across the .NET Mutex class, and that fit our needs beautifully. You define a string which becomes your identifier, and then create a Mutex for that identifier. Mutex stands for Mutually Exclusive. If somebody else has Mutex’ed that identified, you’ll get a fail. Here’s the code to add to your static main method:

static void main(string[] args)
{
  string identifier = "MyApplicationIdentifier";
  bool ok;

  Mutex mutex = new Mutex(true, identifier, out ok);

  if (!ok)
  {
    // Message box provides visual feedback for this demo
    MessageBox.Show("This application is already running");
    return;
  }
  else
  {
    // This becomes your application's entry point
  }

  // Don't allow the mutex to be garbage collected when it falls out of scope.
  GC.KeepAlive(mutex);
}