How can i successfully stop a service using c#?

0

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 ?

c#
asked on Stack Overflow Aug 5, 2020 by Debbie.S • edited Aug 5, 2020 by stuartd

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0