diff --git a/test/Microsoft.NET.Sdk.Publish.Tasks.Tests/EndToEnd/ProcessWrapper.cs b/test/Microsoft.NET.Sdk.Publish.Tasks.Tests/EndToEnd/ProcessWrapper.cs index dcffe58f35db..1d6ad3b9622a 100644 --- a/test/Microsoft.NET.Sdk.Publish.Tasks.Tests/EndToEnd/ProcessWrapper.cs +++ b/test/Microsoft.NET.Sdk.Publish.Tasks.Tests/EndToEnd/ProcessWrapper.cs @@ -1,7 +1,7 @@ using System; using System.Diagnostics; using System.IO; -#if NET472 +#if NETFRAMEWORK using System.Management; #endif @@ -47,39 +47,63 @@ public class ProcessWrapper public static void KillProcessTree(int processId) { + Process process; try { - Process process = Process.GetProcessById(processId); - if (process != null && !process.HasExited) - { - KillProcessTreeInternal(processId); - } + process = Process.GetProcessById(processId); } - catch (Exception) + catch (ArgumentException) { + // Process might have already exited. + return; } + using (process) + { + try + { + if (!process.HasExited) + { +#if NETFRAMEWORK + KillProcessTreeInternal(process.Id); +#else + process.Kill(entireProcessTree: true); +#endif + } + } + catch + { + } + } } +#if NETFRAMEWORK private static void KillProcessTreeInternal(int pid) { -#if NET472 - ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid); - ManagementObjectCollection moc = searcher.Get(); - foreach (ManagementObject mo in moc) + using (ManagementObjectSearcher searcher = new("Select * From Win32_Process Where ParentProcessID=" + pid)) + using (ManagementObjectCollection moc = searcher.Get()) { - KillProcessTreeInternal(Convert.ToInt32(mo["ProcessID"])); + foreach (ManagementObject mo in moc) + { + using (mo) + { + KillProcessTreeInternal(Convert.ToInt32(mo["ProcessID"])); + } + } } -#endif + try { - Process proc = Process.GetProcessById(pid); - proc.Kill(); + using (Process proc = Process.GetProcessById(pid)) + { + proc.Kill(); + } } catch (ArgumentException) { - // vramak: Process might have already exited. + // Process might have already exited. } } +#endif } }