简体   繁体   中英

How to kill a process launched from a thread (created by threadpool) in C#?

I have written a windows service, which monitors a database table for pending jobs and spawns threads to run those jobs and each of these threads in turn launches a process to do the actual work (the process is a Microsoft utility, not a custom one). This works fine, but if one of the jobs is taking longer than usual, I would like to kill that job.

How can this be done? Do I need to abort the thread OR kill the process launched by the thread? I also need to save the standard output of that process in a text file. I use the following code to do that.

using (Process process = Process.Start(startInfo))
{
    LogToTextFile(process.StandardOutput.ReadToEnd());
    process.WaitForExit();
    exitCode = process.ExitCode;
}

Is it possible for the thread to check a flag in the same table and kill the running process, so that it doesn't need to be aborted? I use ThreadPool.QueueUserWorkItem to create a thread. What is the most reliable to way to stop these running processes without stopping the windows service?

Process.Kill is what you're looking for. Killing the thread would be unwise and would have no effect upon the process that it launched.

Assuming you want to wait 60 seconds for the process to finish, you could use this:

using (Process process = Process.Start(startInfo))
{
    LogToTextFile(process.StandardOutput.ReadToEnd());

    if(process.WaitForExit(60000))
    {
        exitCode = process.ExitCode;
    }
    else
    {
        process.Kill();
    }
}

To be doubly clear, do not kill a ThreadPool thread .

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