Search code examples
c#windows-serviceshangfire

Processing jobs in a Windows Service


I've created a Windows Service in C# using HangFire looks like:

using System;
using System.Configuration;
using System.ServiceProcess;
using Hangfire;
using Hangfire.SqlServer;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        private BackgroundJobServer _server;

        public Service1()
        {
            InitializeComponent();

            GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string");
        }

        protected override void OnStart(string[] args)
        {
            _server = new BackgroundJobServer();
        }

        protected override void OnStop()
        {
            _server.Dispose();
        }
    }
}

I'm using VS 2017 on Windows 10. After compiling and service installed successfully but not started! When I try to start manually it gives the famous Error 1053: The service did not respond to the start or control request in a timely fashion.

I found an answer in stackoverflow.com regarding grant permission to NT AUTHORITY\SYSTEM. It does not solve my problem Please help. Thanks.


Solution

  • for Debugging use this pattern:

    1.Add this method into WindowsService1 class:

     public void OnDebug()
     {
        OnStart(null);
     }
    

    2.In Program.cs file change the content to something like it:

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
          #if DEBUG
            var Service = new WindowsService1();
            Service.OnDebug();
          #else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new WindowsService1()
            };
            ServiceBase.Run(ServicesToRun);
          #endif
        }
    }
    

    By this way you can run your code in User Session and check possible problems (Non User-Specific Problems).

    ** Don't put all of your codes on OnStart method. The state of a service will turns to Started whenever OnStart ends.

    ** Use a thread to do you works instead:

        System.Threading.Thread MainThread { get; set; } = null;
        protected override void OnStart(string[] args)
        {
            MainThread = new System.Threading.Thread(new System.Threading.ThreadStart(new Action(()=>{
                // Put your codes here ... 
            })));
            MainThread.Start();
        }
    
        protected override void OnStop()
        {
            MainThread?.Abort();
        }
    

    Most of the times your error is because of this problem.