C#自定义Windows服务无法启动:未响应启动控件

时间:2015-06-01 14:43:29

标签: c# windows service

我一直在关注如何在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();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您的代码不允许OnStart方法终止,因此Windows会认为您的服务尚未正确完成启动任务并报告该错误。您需要在单独的线程上启动程序循环,以便OnStart可以退出

答案 1 :(得分:0)

排序我没有在单独的线程上运行我的服务监视器。修改了我的代码,因为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();
}

然后我将我的服务监视器代码移出Static 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);
        }
    }

现在服务启动,显示器不断运行! :)