Kill some processes by .exe file name

后端 未结 6 930
情深已故
情深已故 2020-11-27 02:45

How can I kill some active processes by searching for their .exe filenames in C# .NET or C++?

6条回答
  •  借酒劲吻你
    2020-11-27 03:10

    My solution is to use Process.GetProcess() for listing all the processes.

    By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:

    var chromeDriverProcesses = Process.GetProcesses().
        Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
        
    foreach (var process in chromeDriverProcesses)
    {
         process.Kill();
    }
    

    Update:

    In case if want to use async approach with some useful recent methods from the C# 8 (Async Enumerables), then check this out:

    const string processName = "chromedriver"; // without '.exe'
    await Process.GetProcesses()
                 .Where(pr => pr.ProcessName == processName)
                 .ToAsyncEnumerable()
                 .ForEachAsync(p => p.Kill());
    

    Note: using async methods doesn't always mean code will run faster, but it will not waste the CPU time and prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.

提交回复
热议问题