Wrapped try statements around programToStop

If a program starts, and then runs another app and then closes itself, then there is a real possibility that the processToStop logic will fail while trying to handle this process. This code now has 3 try/catch statements around it to try and catch this in a friendly way. This should also highlight any issues with the logic and hopefully make it better.
This commit is contained in:
Terry MacDonald 2021-10-31 10:11:14 +13:00
parent 613283da41
commit 1965ef714f

View File

@ -1816,8 +1816,9 @@ namespace DisplayMagician
foreach (Process processToStop in startProgramsToStop.Reverse<Process>())
{
bool stoppedMainProcess = false;
// Stop the process if it hasn't stopped already
try
{
if (!processToStop.HasExited)
{
logger.Debug($"ShortcutRepository/RunShortcut: Stopping process {processToStop.StartInfo.FileName}");
@ -1827,10 +1828,17 @@ namespace DisplayMagician
stoppedMainProcess = true;
}
}
}
catch (Exception ex)
{
logger.Error(ex, $"ShortcutRepository/RunShortcut: Exception while checking if processToStop has already exited");
}
// Next, check whether it had any other processes it started itself
// (copes with loader processes that perform the initial start, then run the main exe)
// If so, we need to go through and find and close all subprocesses
try
{
List<Process> childProcesses = ProcessUtils.FindChildProcesses(processToStop);
if (childProcesses.Count > 0)
{
@ -1850,11 +1858,18 @@ namespace DisplayMagician
ProcessUtils.StopProcess(childProcessToStop);
}
}
}
catch (Exception ex)
{
logger.Error(ex, $"ShortcutRepository/RunShortcut: Exception while checking if processToStop has any child processes");
}
// if the only main process has already exited (e.g. the user exited it themselves)
// then we try to stop any processes with the same name as the application we started
// Look for the processes with the ProcessName we sorted out earlier
// Basically, if we haven't stopped all the children processes, then this is the last gasp
try
{
if (!stoppedMainProcess)
{
string processName = Path.GetFileNameWithoutExtension(processToStop.StartInfo.FileName);
@ -1877,6 +1892,11 @@ namespace DisplayMagician
}
continue;
}
}
catch (Exception ex)
{
logger.Error(ex, $"ShortcutRepository/RunShortcut: Exception while looking for other processes similar to processToStop for us to stop.");
}
}
}