简体   繁体   中英

How to kill a list of processes in c#

I am new to C# and am trying to kill a list of processes. I was able to use the code below to kill one process but would like to change it so that it kills a list of processes. Over time the list will grow so ideally I would like to find a way to do this where updating the list would be quick and easy.

try
{
    foreach (Process proc in Process.GetProcessesByName("notepad"))
    {
        proc.Kill();
    }
}
catch (Exception)
{
    Console.WriteLine("Procces not found.");
}

I'm sorry if I have overlooked a question that was already asked about this. Thank you in advance for any help provided.

The ObservableCollection<T> class provides an event if the collection is changed. So you can create a collection of Process and handle new added items in the event handler:

ObservableCollection<Process> processes = new ObservableCollection<Process>();
processes.CollectionChanged += processes_CollectionChanged;

static void processes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach (var process in e.NewItems.OfType<Process>())
            process.Kill();
    processes.Clear();//remove all Processes from the list
}

But it is not really worth to do it in this way. I think it is more easier to call your code every time you want to kill a process.

The way with the collection is only worthwhile if you change the generic argument to string or int and pass the process name or pid. In this cases, you can determine the Process object in the CollectionChanged event handler and kill them there. (Like in your code.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM