简体   繁体   English

Windows 服务作为本地系统帐户停留在“启动”状态

[英]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:因此,我正在寻找以下两个问题之一的答案:

  1. What should I do to make the service starts properly with a Local System account?我应该怎么做才能使用本地系统帐户正确启动服务?
  2. If I decide to use Network service account, what should I care about to guarantee that my service works properly as a server?如果我决定使用网络服务帐户,我应该注意什么来保证我的服务作为服务器正常工作?

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 -> RunStart -> 键入services.msc并按Enter
  • Look for the service and check the Properties and identify its service name查找服务并检查属性并确定其服务名称
  • Once found, open a command prompt.找到后,打开命令提示符。 Type sc queryex [servicename]键入sc queryex [servicename]
  • Identify the PID (process ID)识别PID(进程ID)
  • In the same command prompt type 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.

相关问题 Windows Service卡在“启动”上 - Windows Service Stuck on “Starting” Windows服务状态为“正在启动” - Windows service status “Starting” Windows服务安装程序用于不同的用户帐户(本地系统除外) - Windows service installer for different user account (other than local system) 在带有“本地系统帐户”的“ Windows服务”下运行时,.NET Windows 7截屏不起作用 - .NET Windows 7 take screenshot not working when running under 'Windows Service' with 'Local System Account' 从服务运行msiexec(本地系统帐户) - Running msiexec from a service (Local System account) C#权限问题导致无法从以本地系统帐户身份运行的Windows服务创建文件夹。 - C# Privilege issues creating folders from Windows service running as Local System account. 在本地系统帐户下的 C# windows 服务中打印 PDF 文件 - printing a PDF file in a C# windows service under Local system account 作为系统帐户运行的 Windows 服务如何获取当前用户的 \AppData\Local\ 特殊文件夹? - How can Windows service running as System account get current user's \AppData\Local\ special-folder? Windows服务在安装时选择用户或系统帐户 - Windows Service Choose User or System Account on Install 我做了一个 Windows 服务,它“有效”但在启动时卡住了 - I have made a Windows service that "works" but is stuck in at starting up
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM