首页 > 解决方案 > 在 Windows 服务中处理作业

问题描述

我使用 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:服务没有及时响应启动或控制请求

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

标签: c#windows-serviceshangfire

解决方案


调试使用此模式:

1.将此方法添加到WindowsService1类中:

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

2.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方法上。服务的状态将在Started任何时候OnStart结束。

** 使用线程来代替您的工作:

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

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


推荐阅读