c# - 在 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 权限的答案。它不能解决我的问题请帮助。谢谢。
解决方案
调试使用此模式:
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();
}
大多数时候你的错误是因为这个问题。
推荐阅读
- python - 如何更改 Seaborn Lineplot 函数中置信区间的填充图案(阴影线)
- python - 将 Collatz 周期运行到一百万,没有处理延迟
- reactjs - 如何将 React 应用程序置于维护模式
- windows-server-2012-r2 - HP Proliant windows server 2012 外部ip
- flutter - 连接到 mysqli 的问题 - 异常:SocketException
- html - 如何对齐我的卡的按钮在中心?
- python - 梯度下降可以近似奇异值分解(SVD)吗?
- git - 对分包商隐藏 git 存储库的内容
- bash - 睡眠:无效的时间间隔 '3\r' shell 脚本
- reactjs - 网格项导致白色间距和水平滚动条React js