Search code examples
c#processpidinstances

how to get PID of my app at runtime using C#


My app checks at startup if any other instance of the same is running already, if yes then it will close all other instances. For this I tried using Process.GetProcessByName("AppName") function and store all the process with AppName in processes[] array. Now i want to find the PID of current instance so that i can close all other instances of my app (which obviously have same name but different PIDs). But i am unable to find that even after lot of googling. Also how can i find the PID of an instance of my app which i have created with Process.Start("AppName.exe") function called from inside AppName.exe


Solution

  • OK, given problems with my other solution, see the following

    In order to hook in between processes, you need some form of IPC. To use the simplicty of shared handles between EventWaitHandles, you could make each program listen for a cancellation flag.

    public static EventWaitHAndle CancellationEvent =
        new EventWaitHandle(
            false,
            EventResetMode.AutoReset,
            "MyAppCancel");
    private object lockObject = new object();
    

    And later...

    Task.Run(() =>
    {
        while(true)
        {
            CancellationEvent.WaitOne();
            lock(lockObject)
                if(!thisIsCalling)    // static bool to prevent this program from ending itself
                    Environment.Exit(0);
        }
    }
    

    And then call the cancellation like so

    lock(lockObject)
    {
        thisIsCalling = true;
        CancellationEvent.Set();
        thisIsCalling = false;
    }