c#自定义Windows服务启动失败:没有响应启动控件

本文关键字:启动 响应 控件 失败 自定义 Windows 服务 | 更新日期: 2023-09-27 17:52:15

我一直在学习如何用c#构建Windows服务应用程序。我的服务的目标是监视另一个windows服务,并尝试启动它(如果它已停止)。我相信它应该可以工作,但是由于某些原因,服务没有启动并且出现错误:

错误1503:服务没有及时响应启动或控制请求。

我希望有人能给我指点一下正确的方向。欢迎任何提示/指导!

下面是我的代码:
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();
        }
    }
}

c#自定义Windows服务启动失败:没有响应启动控件

你的代码不允许OnStart方法终止,所以Windows会认为你的服务没有正确完成它的启动任务并报告该错误。你需要在一个单独的线程上启动你的程序循环,这样OnStart才能退出

我没有在一个单独的线程上运行我的服务监视器。修改我的代码,使OnStart方法是:

/// <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();
}

然后我将我的服务监视器代码移出我的静态Void Main方法,并创建了一个名为ServiceMonitor的新方法,该方法在无限循环中运行:

    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);
        }
    }

服务现在启动并且监视器持续运行!:)