there a lots of different examples floating around SO using mutex, Environment.Exit(0) (Console app), Application.Exit() (Win forms) and lot’s of post saying not to use process.kill().
Could someone explain the political incorrectness of how I am closing OTHER instances of my application. It is a windows forms app. This appears to be working perfectly on my local environment, but I am scared that there are some robust issues I am not aware of.
// I get the current process name and ID
string currentProcName = Process.GetCurrentProcess().ProcessName;
int currentProcID = Process.GetCurrentProcess().Id;
// I then get a list of all process running under this name
Process[] currentProcess = Process.GetProcessesByName(currentProcName);
foreach (Process proc in currentProcess)
{
// if the found process id is using the same name, but not this current id, kill it.
if (proc.Id != currentProcID)
{
proc.Kill(); // Documentation says it imediatly stops the associated process.
proc.Close(); // Documentation says that it frees all resources associated with this component
}
}
As per documentation, I would think this is a reasonable way to close OTHER instances of the running application. Could some more experienced point out some issues if their is any? Aside from atomicity, as I will add in exception handling.
I must defer to Raymond Chen here for reference:
Closing a process in a cooperative manner is by far the best way to get rid of it: It allows for the proper shutdown/closing to occur. Killing a process basically calls
TerminateProcess, which flat-out stops whatever it is doing and kills the bugger.