在 Windows 服务中处理作业

Processing jobs in a Windows Service

我使用 HangFire 在 C# 中创建了一个 Windows 服务,如下所示:

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

我在 Windows 10 上使用 VS 2017。 编译后服务安装成功但没有启动! 当我尝试手动启动时,它给出了著名的错误 1053:服务没有及时响应启动或控制请求

我在 whosebug.com 中找到了关于授予 NT AUTHORITY\SYSTEM 权限的答案。它不能解决我的问题 请帮忙。谢谢

对于调试 使用此模式:

1.Add这个方法变成WindowsService1class:

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

2.In Program.cs 文件将内容更改为类似的内容:

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

通过这种方式,您可以 运行 您在用户会话中的代码并检查可能存在的问题 (非用户特定问题)

** 不要将所有代码都放在 OnStart 方法上。每当 OnStart 结束时,服务的状态将变为 Started

** 使用一个线程代替你工作:

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

大多数时候你的错误是因为这个问题。