var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
foreach (var process in Process.GetProcessesByName("WINWORD"))
{
// Temp is a document which you need to kill.
if (process.MainWindowTitle.Contains("Temp"))
process.Kill();
}
取决于有多少个进程需要杀死(例如,当有数百个进程时,就像我的情况一样) ,对所有这些进程进行搜索可能需要相当长的时间。(有趣的旁注: 而 Kill ()通常在。NET FW 4.8,不知何故,在 NET 6.0 Windows 中要慢得多-在调试/跟踪中看到多个 Win32Exception,直到目标进程最终完成)
言归正传:
在应用程序关闭的情况下,您需要确保每个进程都消失了,可以考虑使用 TAP 库-特别是并行快捷方式,数百个进程在一瞬间被关闭。
用法例子:
var procs = Process.GetProcessByName("mydirtyprocesses");
if (procs.Length == 0) return;
procs.AsParallel().ForAll(process =>
{
try
{
process.Kill();
// No process linked to the process comp (mostly because the process died in
// the short timespan between invoking GetProcess() and the effective
// initialization of the props/fields of the component. -OR- Process has
// already exited (when the exit happened after the process component has
// beenpopulated (difference is, in case 1 you cannot even get the Process
// ID from // the component, in case 2 you see data like Id and get the true
// for HasExited // - so always be prepared for that.
// catch (InvalidOperationException)
{
// Process is gone, no further action required
return;
}
// Ensuring process is gone (otherwise try again or fail or whatever)
if (!process.HasExited)
{
// Handle it
}
}