简体   繁体   中英

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

Why don't you just check equality with your current process?

var processes = Process.GetProcessByName("AppName");

foreach (var p in processes)
{
    if (p != Process.GetCurrentProcess())
       p.CloseMainWindow(); 
}

If you're interested in closing other instances of your app, why not do the opposite and prevent multiple instances from opening in the first place? Using EventWaitHandle can do this thusly:

bool created;
var eve = new System.Threading.EventWaitHandle(
    false,
    EventResetMode.AutoReset,
    "MyAppHandle",
    out created);
if(!created)
{
    eve.Set();
    Environment.Exit(-1); // Always use an exit error code if you're expecting to call from the console!
}

The handle parameter, "MyAppHandle" in this case, will be shared across the entire system, thus meaning not only will the out created paramete be false on secondary instaces, but you can use eve.Set() to cause the handle to fire acorss application. Set up a listening thread and this can allow a message loop to display a message when you attempt to open second instance.

Task.Run(() =>
{
    while(true)
    {
        eve.WaitOne();
        // Display an error here
    }
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM