[英]Windows Service stuck on "starting" status as local system account
I developed a http server via console application in C# and decided to turn it into a Windows service to be able to initialize it without the need to login the machine.我通过 C# 中的控制台应用程序开发了一个 http 服务器,并决定将其转换为 Windows 服务,以便无需登录机器即可对其进行初始化。
I followed all the steps in How to create Windows Service and chose the account as "Local System", but when I install in my server machine and push the start button it takes a while and gives the following error:我按照如何创建 Windows 服务中的所有步骤并选择帐户作为“本地系统”,但是当我在我的服务器机器上安装并按下开始按钮时,它需要一段时间并给出以下错误:
Erro 1053: The service did not respond to the start or control request in timely fashion.
错误 1053:服务没有及时响应启动或控制请求。
After that, the service status stays stuck in "starting" and the application don't work and I can't even stop the service anymore.之后,服务状态停留在“正在启动”,应用程序无法运行,我什至无法停止服务。
Trying to work around this problem, I changed it to "Network Service", so it started normally, but the application was not listening in the port I set when I checked in the prompt with the command "netstat -an".试图解决此问题,我将其更改为“网络服务”,因此它可以正常启动,但是当我使用命令“netstat -an”检查提示符时,应用程序没有侦听我设置的端口。 But the application listens normally if i run it as a console application.
但是,如果我将其作为控制台应用程序运行,该应用程序会正常侦听。
So I am looking for an answer to one of these two questions:因此,我正在寻找以下两个问题之一的答案:
When I converted my console application to windows service I simply put my code directly in the OnStart method.当我将控制台应用程序转换为 Windows 服务时,我只是将代码直接放在 OnStart 方法中。 However, I realized the OnStart method should start the service, but needs to end some time to the service indeed start.
但是,我意识到 OnStart 方法应该启动服务,但需要结束一段时间才能真正启动服务。 So I created a thread that runs my service and let the OnStart method finish.
所以我创建了一个线程来运行我的服务并让 OnStart 方法完成。 I tested and the service worked just fine.
我测试过,服务运行得很好。 Here is how it was the code:
代码如下:
protected override void OnStart(string[] args)
{
Listener(); // this method never returns
}
Here is how it worked:这是它的工作原理:
protected override void OnStart(string[] args)
{
Thread t = new Thread(new ThreadStart(Listener));
t.Start();
}
But I still don't understand why the service ran (passed the "starting" status, but didn't work) when I used network service account.但是我仍然不明白为什么我使用网络服务帐户时服务运行(通过了“启动”状态,但没有工作)。 If anyone knows, I'll be glad to know the reason.
如果有人知道,我会很高兴知道原因。
If you have a service that is not responding or showing pending in Windows services that you are unable to stop, use the following directions to force the service to stop.如果您的某个服务没有响应或在您无法停止的 Windows 服务中显示挂起,请使用以下说明强制停止该服务。
Start
-> Run
or Start
-> type services.msc
and press Enter Start
-> Run
或Start
-> 键入services.msc
并按Entersc queryex [servicename]
sc queryex [servicename]
taskkill /pid [pid number] /f
taskkill /pid [pid number] /f
检查 Windows 应用程序事件日志,它可能包含来自服务自动生成的事件源的一些条目(应该与服务具有相同的名称)。
You can try to increase the windows service timeout with a key in the registry您可以尝试使用注册表中的一个键来增加 Windows 服务超时
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
"ServicesPipeTimeout"=dword:300000 (300 seconds or 5 minutes)
"ServicesPipeTimeout"=dword:300000(300 秒或 5 分钟)
If it doesn't exists it has to be created.如果它不存在,则必须创建它。
For me it was a while loop that looked at an external queue.对我来说,这是一个查看外部队列的 while 循环。 The while-loop continued running until the queue was empty.
while 循环继续运行,直到队列为空。 Solved it by calling a timer event directly only when
Environment.UserInteractive
.仅在
Environment.UserInteractive
时直接调用计时器事件解决了它。 Therefore the service could be debugged easily but when running as a service it would wait for the timers ElapsedEventHandler
event.因此,该服务可以轻松调试,但是当作为服务运行时,它将等待计时器
ElapsedEventHandler
事件。
Service:服务:
partial class IntegrationService : ServiceBase
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private System.Timers.Timer timer;
public IntegrationService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
// Add code here to start your service.
logger.Info($"Starting IntegrationService");
var updateIntervalString = ConfigurationManager.AppSettings["UpdateInterval"];
var updateInterval = 60000;
Int32.TryParse(updateIntervalString, out updateInterval);
var projectHost = ConfigurationManager.AppSettings["ProjectIntegrationServiceHost"];
var projectIntegrationApiService = new ProjectIntegrationApiService(new Uri(projectHost));
var projectDbContext = new ProjectDbContext();
var projectIntegrationService = new ProjectIntegrationService(projectIntegrationApiService, projectDbContext);
timer = new System.Timers.Timer();
timer.AutoReset = true;
var integrationProcessor = new IntegrationProcessor(updateInterval, projectIntegrationService, timer);
timer.Start();
}
catch (Exception e)
{
logger.Fatal(e);
}
}
protected override void OnStop()
{
try
{
// Add code here to perform any tear-down necessary to stop your service.
timer.Enabled = false;
timer.Dispose();
timer = null;
}
catch (Exception e)
{
logger.Fatal(e);
}
}
}
Processor:处理器:
public class IntegrationProcessor
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static volatile bool _workerIsRunning;
private int _updateInterval;
private ProjectIntegrationService _projectIntegrationService;
public IntegrationProcessor(int updateInterval, ProjectIntegrationService projectIntegrationService, Timer timer)
{
_updateInterval = updateInterval;
_projectIntegrationService = projectIntegrationService;
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = _updateInterval;
//Don't wait for first elapsed time - Should not be used when running as a service due to that Starting will hang up until the queue is empty
if (Environment.UserInteractive)
{
OnTimedEvent(null, null);
}
_workerIsRunning = false;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
try
{
if (_workerIsRunning == false)
{
_workerIsRunning = true;
ProjectInformationToGet infoToGet = null;
_logger.Info($"Started looking for information to get");
//Run until queue is empty
while ((infoToGet = _projectIntegrationService.GetInformationToGet()) != null)
{
//Set debugger on logger below to control how many cycles the service should run while debugging.
var watch = System.Diagnostics.Stopwatch.StartNew();
_logger.Info($"Started Stopwatch");
_logger.Info($"Found new information, updating values");
_projectIntegrationService.AddOrUpdateNewInformation(infoToGet);
_logger.Info($"Completed updating values");
watch.Stop();
_logger.Info($"Stopwatch stopped. Elapsed seconds: {watch.ElapsedMilliseconds / 1000}. " +
$"Name queue items: {infoToGet.NameQueueItems.Count} " +
$"Case queue items: {infoToGet.CaseQueueItems.Count} " +
$"Fee calculation queue items: {infoToGet.FeeCalculationQueueItems.Count} " +
$"Updated foreign keys: {infoToGet.ShouldUpdateKeys}");
}
_logger.Info($"Nothing more to get from integration service right now");
_workerIsRunning = false;
}
else
{
_logger.Info($"Worker is already running! Will check back again after {_updateInterval / 1000} seconds");
}
}
catch (DbEntityValidationException exception)
{
var newException = new FormattedDbEntityValidationException(exception);
HandelException(newException);
throw newException;
}
catch (Exception exception)
{
HandelException(exception);
//If an exception occurs when running as a service, the service will restart and run again
if (Environment.UserInteractive)
{
throw;
}
}
}
private void HandelException(Exception exception)
{
_logger.Fatal(exception);
_workerIsRunning = false;
}
}
Find PID of Service查找服务的PID
sc queryex <SERVICE_NAME>
sc queryex <SERVICE_NAME>
Give result's below给出结果如下
SERVICE_NAME: Foo.Services.Bar TYPE : 10 WIN32_OWN_PROCESS STATE : 2 0 START_PENDING (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 PID : 3976 FLAGS : SERVICE_NAME: Foo.Services.Bar TYPE : 10 WIN32_OWN_PROCESS STATE : 2 0 START_PENDING (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0x 6 PID 0x70x00x 0x00x 0x00x 0x00x000
Now Kill the Service:现在终止服务:
taskkill /f /pid 3976
taskkill /f /pid 3976
SUCESS: The process with PID 3976 has been terminated.成功:PID 为 3976 的进程已终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.