How to terminate a process cleanly from a background service

Andy Reynolds 20 Reputation points
2023-01-30T16:28:06.2466667+00:00

I have developed a program which runs as a Windows service. This program starts a process to run another exe file. It's developed in C# with .NET 6.0.

I know I can use

Process.Kill()

to terminate the process, but I'd like to try to end the process cleanly before killing it. I've read through several other threads, but haven't found a solution that works. The exe file that is run as a process does not have a GUI, so CloseMainWindow doesn't work. Here is the code where I start the process. When a CancellationToken arrives, the loop exits and the service tries to end the exe process.

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "otherprogram.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;

// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
    bool exited = false;
    while (!stoppingToken.IsCancellationRequested && !exited)
    {
        exited = exeProcess.WaitForExit(1000);
    }
    if (!exited)
    {
        exeProcess.CloseMainWindow();  // THIS DOES NOT WORK!!!!
        exited = exeProcess.WaitForExit(5000);
    }
    if (!exited)
    {
        exeProcess.Kill();
        exited = exeProcess.WaitForExit(5000);
    }
}

Any suggestions or pointers to other threads would be greatly appreciated. Thank you!

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,248 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,021 Reputation points
    2023-01-30T18:20:16.0633333+00:00

    the easiest is to redirect the console, and send an exit command,

    0 comments No comments