- 1 year ago
Stop a Windows service and wait for it to stop by itself as opposed to get it killed by Windoes after +-15sec
To stop a Windows service and wait for it to stop gracefully, you can use the following steps:
Import the necessary namespaces:
csharpusing System;
using System.ServiceProcess;
using System.Threading;
Define a function to stop the service and wait for it to stop:
csharpstatic void StopServiceAndWait(string serviceName)
{
using (ServiceController serviceController = new ServiceController(serviceName))
{
// Check if the service is running
if (serviceController.Status != ServiceControllerStatus.Stopped)
{
// Stop the service
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMinutes(1)); // Adjust the timeout as needed
}
}
}
Call the
StopServiceAndWait
function with the name of the service you want to stop:csharpstring serviceName = "YourServiceName"; // Replace with the actual service name
StopServiceAndWait(serviceName);
In the above code, the StopServiceAndWait
function stops the specified Windows service using the ServiceController
class. It first checks if the service is already stopped. If it is running, it stops the service and waits for it to reach the Stopped
state, with a specified timeout period (in this case, 1 minute).
Make sure to replace "YourServiceName"
in the code with the actual name of the Windows service you want to stop.
By using this approach, the code will allow the service to gracefully stop within the specified timeout period before proceeding with further actions.