xzk
xzk

Reputation: 877

Could not Start up Windows Service after Installation

I followed this article to build my windows service apps.

https://learn.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

Now my project directory has MyService.cs and ProjectInstaller.cs. Both contains a Designer.cs and a .resx file.

After building the project, I copied everything under /bin/Debug to server, and ran the InstallUtil command to install it.

I could see my service in Services list, but when I click Start, it will take long time to start until it gets timed-out.

My Program.cs file is simple as normal

public static void Main()
        {


#if DEBUG

            MyService mySvc = new MyService();
            mySvc.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new MyService() 
            };
            ServiceBase.Run(ServicesToRun);
#endif
        }

In MyService.cs:

public partial class MyService : ServiceBase
    {
        private bool stopping = false;
        private Int32 timeInterval = 0;
        private ManualResetEvent stoppedEvent;
        public static IServiceProvider svcProvider = null;

        public MyService()
        {
            InitializeComponent();
            stopping = false;
            stoppedEvent = new ManualResetEvent(false);
            LoadDIStartup();
        }

        public void OnDebug()
        {
            StartServiceWorkerMainProcess();
        }

        protected override void OnStart(string[] args)
        {
            stopping = false;
            StartServiceWorkerMainProcess();
        }

        protected override void OnStop()
        {
            stopping = true;
            StopServiceWorkerMainProcess();
            stoppedEvent.WaitOne(); //Wait for the finish of the ServiceWorkerThread
        }

        /// <summary>
        /// The function called in the start event of the the service. And when in Visual Studio Debug Mode run.
        /// </summary>
        public void StartServiceWorkerMainProcess()
        {
            try
            {
                timeInterval = AppConfig.TimeInterval;
                // Queue the SubWorker for execution in a worker thread. 
                ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceWorkerSub));
            }
            catch (Exception e)
            {
                AppLogger.LogError(" Error while launching the WorkerSub thread. " + "\n" + e.Message + "\n" + e.InnerException + " \n" + e.StackTrace + "\n" + e.Source + "\n");

            }
        }

        /// <summary>
        /// The function called in the stop event of the the service
        /// </summary>
        public void StopServiceWorkerMainProcess()
        {
            AppLogger.LogInfo(" Service Stopped at " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "\n");
        }

        private async void ServiceWorkerSub(object state)
        {
            try
            {
                // Periodically check if the service is stopping
                while (!stopping)
                {
                    try
                    {
                        //Do my Stuff (FYI, Mutex is used here.)
                        AppLogger.LogInfo("DONE. About to sleep.");
                    }
                    catch (Exception e)
                    {
                        AppLogger.LogError(" Error. " + "\n" + e.Message + "\n" + e.InnerException + " \n" + e.StackTrace + "\n" + e.Source + "\n");

                    }
                    Thread.Sleep(timeInterval);
                }
                // Signal the stopped event
                stoppedEvent.Set();
            }
            catch (Exception e)
            {
                AppLogger.LogError(" Error in ServiceWorkerSub. " + "\n" + e.Message + "\n" + e.InnerException + " \n" + e.StackTrace + "\n" + e.Source + "\n");

            }
        }

        private static void LoadDIStartup()
        {
            //Dependency Injection Setup Start
            // blah blah. DI using json files. 
            //Dependency Injection Setup End

        }
    }

In Designer view, MyService.cs has a serviceController1 and I set serviceName = TestService. ProjectInstaller.cs has a serviceProcessInstaller1 and serviceInstaller1. The serviceName property in serviceInstaller1 is TestService as well.

The Project has several properties file inside and it runs well locally.

Any problem with my setup?

Upvotes: 0

Views: 162

Answers (2)

vasily.sib
vasily.sib

Reputation: 4002

You need to notify a Service Control Manager, that your service has successfully started in your OnStart method. Windows 7/8/10 ignores this, but Windows Server is deciding that your service haven't start properly, so it waits for a timeout and kill your service process.

Read "Setting Service Status" part of article by the link you provided.

Upvotes: 0

Ross Bush
Ross Bush

Reputation: 15185

When you build your installer make sure you are in release mode else your #if DEBUG logic kicks in.

Upvotes: 1

Related Questions