I am trying to stop a service using the following code:
public static void StopService(string name, out string message)
{
message = string.Empty;
EndTask();
ServiceController sc = new ServiceController();
sc.ServiceName = name;
if (sc.Status == ServiceControllerStatus.Running)
{
try
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}
catch (Exception e)
{
throw ex;
}
}
else
{
message = $"The service has been stopped.";
}
}
The EndTask() is defined as follows:
public static void EndTask()
{
string taskname = "myservice.exe";
string processName = taskname.Replace(".exe", "");
foreach (Process process in Process.GetProcessesByName(processName))
{
process.Kill();
}
}
But I occasionally get the following error
Cannot stop mytestservice service on computer '.'.
Inner Exception: System.ComponentModel.Win32Exception (0x80004005): The pipe has been ended"
Is this to do with the EndTask routine ? do i need to run the EndTask() asynchronously ?
User contributions licensed under CC BY-SA 3.0