C# 错误 1053 服务没有响应启动或控制请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1673545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:53:07  来源:igfitidea点击:

Error 1053 the service did not respond to the start or control request

c#windowserror-handlingwindows-services

提问by Alex

I've written a Windows Service in C# that basically checks my db every minute for orders, generates a PDF from these orders, and emails it.

我用 C# 编写了一个 Windows 服务,它基本上每分钟检查一次我的数据库是否有订单,从这些订单生成一个 PDF,然后通过电子邮件发送。

The logic works perfectly in my tests etc..

该逻辑在我的测试等中完美运行。

When i create the service, and install it using the setup project, when I go to start the service in the services mmc, I get:

当我创建服务并使用安装项目安装它时,当我在服务 mmc 中启动服务时,我得到:

error 1053 the service did not respond to the start or control request in a timely fashion

错误 1053 服务没有及时响应启动或控制请求

My OnStart method looks like this:

我的 OnStart 方法如下所示:

protected override void OnStart(string[] args)
{
    //writeToWindowsEventLog("Service started", EventLogEntryType.Information);
    timer.Enabled = true;
}

Basically, just enables the timer... so theres no process intensive call there.

基本上,只启用计时器......所以那里没有过程密集型调用。

Where am I going wrong?

我哪里错了?

I've tried setting the startup account to local system, network service etc... nothing works!

我试过将启动帐户设置为本地系统、网络服务等......没有任何效果!

Edit:

编辑:

Here is my code: (processPurchaseOrders is the method where the db is queried and pdf's are generated etc...)

这是我的代码:(processPurchaseOrders 是查询数据库和生成 pdf 的方法等...)

public partial class PurchaseOrderDispatcher : ServiceBase
{
    //this is the main timer of the service
    private System.Timers.Timer timer;

    public PurchaseOrderDispatcher()
    {
        InitializeComponent();
    }

    // The main entry point for the process
    static void Main()
    {
      #if (!DEBUG)
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new PurchaseOrderDispatcher() };
        ServiceBase.Run(ServicesToRun);
      #else //debug code
        PurchaseOrderDispatcher service = new PurchaseOrderDispatcher();
        service.processPurchaseOrders();
      #endif
    }

    private void InitializeComponent()
    {
        this.CanPauseAndContinue = true;
        this.ServiceName = "Crocus_PurchaseOrderGenerator";
    }

    private void InitTimer()
    {
        timer = new System.Timers.Timer();

        //wire up the timer event
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

        //set timer interval
        var timeInSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["TimerIntervalInSeconds"]);
        timer.Interval = (timeInSeconds * 1000); // timer.Interval is in milliseconds, so times above by 1000

        timer.Enabled = true;
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
            components.Dispose();

        base.Dispose(disposing);
    }

    protected override void OnStart(string[] args)
    {
        //instantiate timer
        Thread t = new Thread(new ThreadStart(this.InitTimer));
        t.Start();
    }

    protected override void OnStop()
    {
        //turn off the timer.
        timer.Enabled = false;
    }

    protected override void OnPause()
    {
        timer.Enabled = false;

        base.OnPause();
    }

    protected override void OnContinue()
    {
        timer.Enabled = true;

        base.OnContinue();
    }

    protected void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        processPurchaseOrders();
    }
}

采纳答案by SwDevMan81

From MSDN:
"Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called."

If your timer is not initialized in the OnStart call, this could be a problem. I would also check the type of timer, make sure its a System.Timers.Timer for Services. Hereis an example of how to setup the timer in a windows service.

来自MSDN
“不要使用构造函数来执行应该在 OnStart 中的处理。使用 OnStart 来处理服务的所有初始化。构造函数在应用程序的可执行文件运行时调用,而不是在服务运行时调用。可执行文件在 OnStart 之前运行。例如,当您继续时,不会再次调用构造函数,因为 SCM 已经将对象保存在内存中。如果 OnStop 释放在构造函数中而不是在 OnStart 中分配的资源,则第二次服务将不会再次创建所需的资源叫。”

如果您的计时器未在 OnStart 调用中初始化,则这可能是一个问题。我还会检查计时器的类型,确保它是用于服务的 System.Timers.Timer。这里是如何在 Windows 服务中设置计时器的示例。

//TODONT: Use a Windows Service just to run a scheduled process

//TODONT:仅使用 Windows 服务来运行预定进程

I tried your code, and it seems ok. The only difference I had was to hard code the timer value (Service1.cs). Let me know if the below doesnt work.

我试过你的代码,看起来没问题。我唯一的区别是硬编码计时器值 (Service1.cs)。如果以下不起作用,请告诉我。

Service1.cs

服务1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Threading;

namespace WindowsServiceTest
{
    public partial class Service1 : ServiceBase
    {
        private System.Timers.Timer timer;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //instantiate timer
            Thread t = new Thread(new ThreadStart(this.InitTimer)); 
            t.Start();
        }

        protected override void OnStop()
        {
            timer.Enabled = false;
        }

         private void InitTimer()  
         {     
             timer = new System.Timers.Timer();  
             //wire up the timer event 
             timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
             //set timer interval   
             //var timeInSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["TimerIntervalInSeconds"]); 
             double timeInSeconds = 3.0;
             timer.Interval = (timeInSeconds * 1000); 
             // timer.Interval is in milliseconds, so times above by 1000 
             timer.Enabled = true;  
         }

        protected void timer_Elapsed(object sender, ElapsedEventArgs e) 
        {
            int timer_fired = 0;
        }
    }
}

Service1.Designer.cs

Service1.Designer.cs

namespace WindowsServiceTest
{
    partial class Service1
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "Service1";
            this.CanPauseAndContinue = true;
        }

        #endregion
    }
}

I just created a blank Windows Service project and add the below so I could run installutil.exe and attach to the above to see if the event was firing (and it did).

我刚刚创建了一个空白的 Windows 服务项目并添加了以下内容,以便我可以运行 installutil.exe 并附加到上面的内容以查看事件是否正在触发(并且确实发生了)。

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.ServiceProcess;

namespace WindowsServiceTest
{
    [RunInstaller(true)]
    public class MyServiceInstaller : System.Configuration.Install.Installer
    {
        public MyServiceInstaller()
        {
            ServiceProcessInstaller process = new ServiceProcessInstaller();

            process.Account = ServiceAccount.LocalSystem;

            ServiceInstaller serviceAdmin = new ServiceInstaller();

            serviceAdmin.StartType = ServiceStartMode.Manual;
            serviceAdmin.ServiceName = "Service1";
            serviceAdmin.DisplayName = "Service1 Display Name";
            Installers.Add(process);
            Installers.Add(serviceAdmin);
        }
    }
}

回答by ChrisCa

I just had the same problem.

我只是遇到了同样的问题。

It turned out it was because I was running it as a console in debug mode - like the code you have above

原来是因为我在调试模式下将它作为控制台运行 - 就像你上面的代码

#if (!DEBUG)

#else //debug code

#endif

And I had compiled it in debug mode and installed the service

我在调试模式下编译它并安装了服务

When I compiled it in release mode it worked as expected

当我在发布模式下编译它时,它按预期工作

Hope this helps

希望这可以帮助

回答by vnRock

I go to the server console (in the server room) and start the service from there. Remote in wont' work.

我转到服务器控制台(在服务器机房中)并从那里启动服务。远程无法工作。

回答by AndyClaw

The constructor was the issue for me. The constructor must have been throwing an excpetion about missing DLLs.

构造函数对我来说是个问题。构造函数必须抛出一个关于缺少 DLL 的异常。

My issue: my inexperience with creating installers. I didn't have the dependent DLLs being copied into the install folder (I needed to select Release build configuration when creating Primary Project Output).

我的问题:我缺乏创建安装程序的经验。我没有将依赖的 DLL 复制到安装文件夹中(我需要在创建主项目输出时选择发布构建配置)。

回答by SyntaxError

Also had this error until I found out that there's an excess ">" character on my .config file.

也有这个错误,直到我发现我的 .config 文件中有一个多余的“>”字符。

So, try to double check your .config file first before punching your computer ;)

所以,在打你的电脑之前,先试着仔细检查你的 .config 文件;)

回答by Aaron

In case anyone else runs across this in the future, I received the same Error 1053 when trying to start my Windows service on Windows Server 2012.

以防其他人将来遇到此问题,当我尝试在 Windows Server 2012 上启动我的 Windows 服务时收到相同的错误 1053。

The issue ended up being that the service was developed targeting the .NET framework 4.5.1, but the Windows Server 2012 instance did not have that version of the .NET framework installed. Backing the service down to target .NET 4.0 fixed the error.

问题最终是该服务是针对 .NET 框架 4.5.1 开发的,但 Windows Server 2012 实例没有安装该版本的 .NET 框架。将服务备份到目标 .NET 4.0 修复了错误。

回答by Orcun

In my case; i was trying to install a .Net 3.5 service to Windows 2012 server. In the server the .Net 4.0 framework was installed.

就我而言;我试图在 Windows 2012 服务器上安装 .Net 3.5 服务。在服务器中安装了 .Net 4.0 框架。

I change my target framework of service to .Net 4.0. Now it works fine.

我将我的目标服务框架更改为 .Net 4.0。现在它工作正常。

回答by Jarekczek

The first thing that is executed from the assembly containing the service is the Mainmethod . And it must take special actions, or at least one such action:

从包含服务的程序集中执行的第一件事是Main方法。并且它必须采取特殊行动,或至少采取一种这样的行动:

public static int Main()
{
  Run(new System.ServiceProcess.ServiceBase[] { new YourServiceClass() });
}

That's what I discovered after trials and errors session when creating my first service. I didn't use VS. I did use VS guide (Walkthrough: Creating a Windows Service Application in the Component Designer), while I should rather use this one: Creating a C# Service Step-by-Step: Lesson I.

这就是我在创建我的第一个服务时经过反复试验后发现的。我没有使用VS。我确实使用了 VS 指南(演练:在组件设计器中创建 Windows 服务应用程序),而我更应该使用这个指南:创建 C# 服务循序渐进:第 I 课

Without suitable 'Main' method the executable finishes immediately and system reports that 30 seconds timeout was exceeded :)

如果没有合适的“Main”方法,可执行文件会立即完成,并且系统报告超过 30 秒超时:)

回答by Jarekczek

This worked for me. Basically make sure the Log on user is set to the right one. However it depends how the account infrastructure is set. In my example it's using AD account user credentials.

这对我有用。基本上确保登录用户设置为正确的用户。但是,这取决于帐户基础结构的设置方式。在我的示例中,它使用 AD 帐户用户凭据。

In start up menu search box search for 'Services' -In Services find the required service -right click on and select the Log On tab -Select 'This account' and enter the required content/credentials -Ok it and start the service as usual

在启动菜单搜索框中搜索“服务”-在“服务”中找到所需的服务-右键单击并选择“登录”选项卡-选择“此帐户”并输入所需的内容/凭据-确定并照常启动服务

enter image description here

在此处输入图片说明

回答by Ruben Collazos

Like me. In 4.6.1 do not work (I have the same message). Then I try in 4.5 and work fine.

像我这样的。在 4.6.1 中不起作用(我有相同的消息)。然后我在 4.5 中尝试并正常工作。