【问题标题】:Processing jobs in a Windows Service在 Windows 服务中处理作业
【发布时间】:2023-03-03 15:28:02
【问题描述】:

我使用 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 权限的答案。它不能解决我的问题 请帮忙。谢谢。

【问题讨论】:

  • (如果“SQL 服务器”运行在同一台机器上,您是否告诉 SCM 您的服务依赖于它?)

标签: c# windows-services hangfire


【解决方案1】:

调试使用这个模式:

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 方法上。每当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();
    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 2014-09-28
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多