Rawns Rawns -4 years ago 214
C# Question

C# Custom Windows service failed to start: Did not respond to the start control

I've been following a few tutorials on how to build a Windows service app in C#. My goal for my service is to monitor another windows service and attempt to start it, if it is stopped. I believe it should work but for some reason the service is not starting and errors:


Error 1503: The service did not respond to the start or control request in a timely fashion.


I'm hopeful someone can give me a pointer in the right direction here. Any pointers/guidance welcome!

Here is my code:

using System;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;

namespace AEMKeepAlive
{
class AEMKeepAlive : ServiceBase
{
/// <summary>
/// Public Constructor for WindowsService.
/// - Put all of your Initialization code here.
/// </summary>
public AEMKeepAlive()
{
this.ServiceName = "AEM Keep Alive Service";
WriteErrorLog("----------Service started!----------");

// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
this.CanShutdown = true;
this.CanStop = true;
}

/// <summary>
/// Anter messages into a log file
/// </summary>
public static void WriteErrorLog(string msg)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\AEMKeepAlive.log", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + msg);
sw.Flush();
sw.Close();
}
catch
{
}
}

/// <summary>
/// The Main Thread: This is where your Service is Run.
/// </summary>
static void Main()
{

ServiceController myService = new ServiceController();
myService.ServiceName = "CagService";
string svcStatus = myService.Status.ToString();

if (svcStatus == "Running")
{
WriteErrorLog("AEM Service is running! Sleeping for 60 seconds...");
}
else if (svcStatus == "Stopped")
{
WriteErrorLog("WARNING: AEM Service is stopped! Attempting to start the AEM service...");
myService.Start();

string svcStatusWas = "";
while (svcStatus != "Running")
{
if (svcStatus != svcStatusWas)
{
Console.WriteLine("Status: " + svcStatus);
}
svcStatusWas = svcStatus;
myService.Refresh();
svcStatus = myService.Status.ToString();
}
WriteErrorLog("AEM Service has been started! Sleeping for 60 seconds...");
}
else
{
myService.Stop();
WriteErrorLog("Status: " +svcStatus);
while (svcStatus != "Stopped")
{
myService.Refresh();
svcStatus = myService.Status.ToString();
}
WriteErrorLog("WARNING: AEM Service is stopped! Attempting to start the AEM service...");
}
System.Threading.Thread.Sleep(30000);
ServiceBase.Run(new AEMKeepAlive());
}

/// <summary>
/// OnStart(): Put startup code here
/// - Start threads, get inital data, etc.
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
try
{
ServiceBase.Run(new AEMKeepAlive());
base.OnStart(args);
}
catch(Exception e)
{
throw;
}
}

/// <summary>
/// OnStop(): Put your stop code here
/// - Stop threads, set final data, etc.
/// </summary>
protected override void OnStop()
{
WriteErrorLog("----------Service stopped!----------");
base.OnStop();

}

/// <summary>
/// OnShutdown(): Called when the System is shutting down
/// - Put code here when you need special handling
/// of code that deals with a system shutdown, such
/// as saving special data before shutdown.
/// </summary>
protected override void OnShutdown()
{
WriteErrorLog("----------Shutdown initiated----------");
base.OnShutdown();
}
}
}

Answer Source

Sorted I was not running my service monitor on a separate thread. Modified my code as so the OnStart method is:

/// <summary>
/// OnStart(): Put startup code here
///  - Start threads, get inital data, etc.
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
    Library.WriteErrorLog("--------------Service Started--------------");
    Thread MyThread = new Thread(new ThreadStart(ServiceMonitor));
    MyThread.Name = "Worker Thread";
    MyThread.IsBackground = true;
    MyThread.Start();
}

I then moved my service monitor code out of my Static Void Main method and created a new method called ServiceMonitor that runs in an infinite loop:

    public static void ServiceMonitor()
    {
        for (;;)
        {
            // Monitor the CagService
            ServiceController myService = new ServiceController();
            myService.ServiceName = "CagService";
            string svcStatus = myService.Status.ToString();

            // If the CagService is running, add to the log and sleep for 5 minutes
            try
            {
                if (svcStatus == "Running")
                {
                    Library.WriteErrorLog("AEM Service is running! Sleeping for 5 minutes...");
                }

                // If the service is stopped, add to the log file and attempt a restart
                else if (svcStatus == "Stopped")
                {
                    Library.WriteErrorLog("WARNING: AEM Service is stopped! Attempting to start the AEM service...");
                    myService.Start();

                    string svcStatusWas = "";
                    while (svcStatus != "Running")
                    {
                        if (svcStatus != svcStatusWas)
                        {
                            Library.WriteErrorLog("Status: " + svcStatus);
                        }
                        svcStatusWas = svcStatus;
                        myService.Refresh();
                        svcStatus = myService.Status.ToString();
                    }
                    Library.WriteErrorLog("AEM Service has been started! Sleeping for 5 minutes...");
                }

                // If the service has any other status, stop it then restart it. 
                else
                {
                    myService.Stop();
                    Library.WriteErrorLog("Status: " + svcStatus);
                    while (svcStatus != "Stopped")
                    {
                        myService.Refresh();
                        svcStatus = myService.Status.ToString();
                    }
                    Library.WriteErrorLog("WARNING: AEM Service is stopped! Attempting to start the AEM service...");
                }
            }
            catch(InvalidOperationException)
            {
                Library.WriteErrorLog("Invalid Operation Exception! The service cannot be started because it is disabled.");
            }
            System.Threading.Thread.Sleep(300000);
        }
    }

The service now starts and the monitor continually runs! :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download