This program will kill the process a user specifies and start a BackgroundWorker that constantly analyzes a list of running processes and kills it again if it starts. But it will not cancel even when I tell it to.

This is the BackgroundWorker's code.

private void KeepProcessKilled_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                foreach (Process process in Process.GetProcesses())
                {
                    if (process.ProcessName == BadProcessName)
                    {
                        try
                        {
                            process.Kill();
                        }

                        catch
                        {
                        }
                    }
                }
            }
        }

And the code that stops it.

private void DeleteButton_Click(object sender, EventArgs e)
        {
            KeepProcessKilled.CancelAsync();
            ResultsBox.AppendText("KeepProcessKilled procedure has stopped.");
        }

The process continues to use 100 percent of the CPU and slows the system even after it is supposed to. I'm guessing I need to have a break somewhere in the while loop but I'm not sure where to put it or how to get to it when it's supposed to cancel.

Also is there a way to limit the CPU usage? 100 percent seems like a bit much for just checking what processes are running.

Dani AI

Generated

The problem was the tight infinite loop in the DoWork handler: calling BackgroundWorker.CancelAsync only sets a cancellation flag — it does not abort the thread. As suggested and confirmed, the DoWork routine must observe that flag and return cleanly (and set e.Cancel = true) so the worker can finish. (learn.microsoft.com)

A safer, practical DoWork pattern is to poll for the specific process (rather than scanning everything), kill/WaitForExit, dispose the Process objects, and sleep between iterations so the loop does not spin the CPU. The empty catch in the original code hides errors (privileges, access denied, etc.) and should be replaced with targeted handling or at least logging. Example (illustrative):

private void KeepProcessKilled_DoWork(object sender, DoWorkEventArgs e)
{
    var worker = (BackgroundWorker)sender;
    while (!worker.CancellationPending)
    {
        var found = Process.GetProcessesByName(badName);
        foreach (var p in found)
        {
            try { p.Kill(); p.WaitForExit(2000); }
            catch (Exception ex) { /* log/report ex */ }
            finally { p.Dispose(); }
        }
        Thread.Sleep(500); // throttle loop
    }
    e.Cancel = true;
}

Process.Kill is an immediate, forceful termination and can leave state inconsistent; Process objects hold OS handles and should be disposed to avoid leaking handles. (learn.microsoft.com)

For a more efficient, event-driven approach, subscribe to process-start events via WMI (ManagementEventWatcher / Win32_ProcessStartTrace or __InstanceCreationEvent) instead of polling; this avoids both CPU use and racey loops. For newer code, prefer Task + CancellationTokenSource for cooperative cancellation rather than BackgroundWorker. (learn.microsoft.com)

Cautions: repeatedly killing processes can destabilize a system (watchdog/babysitter processes, services, or protected processes may respawn or cause trouble). Run with appropriate privileges, test on noncritical targets, and log results rather than swallowing exceptions.

Recommended Answers

All 4 Replies

The reason your loop eats up the proc is because you are running an infinite loop with While(true) you should be using some kind of reachable goal While(somevalue == true) that way you can break the loop by reaching a goal. If you throw a Thread.Sleep(500) in the loop, you will allow the loop to sleep, easing the usage of the proc and letting the OS prioritize another process for CPU usage.

the cancellation is a little different. you have to put a if statement in the loop, on every itteration you should check the CancelationPending property of the background worker. this will tell you if backgroundworker.CancelAsync has been called.

http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx

It's a fairly simple process.

BTW. its not the best idea to be constantly looping and killing processes. You can put the system in a bad place, especially if the process you are killing has a babysitter or crash protection service attached to it.

Thank you for the quick reply. It works now that I break the while loop when CancellationPending is true, and now it barely uses the processor at all.

BTW. its not the best idea to be constantly looping and killing processes. You can put the system in a bad place, especially if the process you are killing has a babysitter or crash protection service attached to it.

I know, I crashed Windows with it not too long ago and had to start over. :$
This program is assuming the process its killing belongs to a virus and keep it from starting again so it can be deleted. Is it still a dangerous thing then? I doubt viruses would have some kind of crash protection.

Also I don't know what you mean by babysitter. Enlighten me!

sometimes there is a separate process, service, or pool of processes that serve no other purpose but to make sure that no matter a certain process is still running. this is often called a babysitter process. Many many viruses have them. So when you kill it, it starts again.

So long as you identify your bad processes well, then I imagine it can't be any more harmful than the virus itsself.

you still want to throw some thread.sleeps in the loop to slow done the repeat rate.

best of luck.

Thank you for the help. It runs correctly with all programs I have tested it with. Now I need to get a virus to really test it out. Not looking forward to that! :sweat:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.