There Can Be Only One. Or Two. Or Three, but Never Four.

A quick but very simple technique to limit the number of instances of a .NET app that will execute at once:

using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication1 {
  public class Program {
    static void Main(string[] args) {


      var myProcessName = Process.GetCurrentProcess().ProcessName;
      Process[] processes = Process.GetProcesses();
      var howManyOfMe = processes.Where(p => p.ProcessName == myProcessName).Count();
      if (howManyOfMe > MAX_PERMITTED_INSTANCES) {
        Console.WriteLine("Too many instances - exiting!");
      } else {
        Console.WriteLine("I'm process #{0} and I'm good to go!", howManyOfMe);
        /* do heavy lifting here! */

Very handy if – like we do – you’re firing off potentially expensive encoding jobs every few minutes via a scheduled task, and you’re happy for 3-4 of them to be running at any one time – hey, that’s what multicore CPUs are for, right? - but you’d rather not end up with 37 instances of encoder.exe all fighting for your CPU cycles like cats fighting for the last bit of bacon.

I’m still sometimes really, really impressed at how easy stuff like this is in .NET… I thought this would end up being hours of horrible extern/Win32 API calls, but no. It’s that easy. Very nice.