【问题标题】:Error 1053 the service did not respond to the start or control request错误 1053 服务没有响应启动或控制请求
【发布时间】:2023-03-23 21:01:01
【问题描述】:

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

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

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

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

我的 OnStart 方法如下所示:

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

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

我哪里出错了?

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

编辑:

这是我的代码:(processPurchaseOrders 是查询 db 并生成 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();
    }
}

【问题讨论】:

  • 你的构造函数中有什么?问题可能就在那里。
  • 我的构造函数中只有 this.CanPauseAndContinue = true; this.ServiceName = "Crocus_PurchaseOrderGenerator";
  • 你在哪里实例化计时器?看看我在下面发布的示例 (clifgriffin.com/2008/11/20/using-timers-in-a-c-windows-service),了解如何在 Windows 服务中设置计时器
  • 我编辑了问题并添加了所有代码......
  • 我使用您的大部分代码通过一个完整的示例更新了我的答案。它开始正常,我能够附加并看到事件正在触发。

标签: c# windows error-handling windows-services


【解决方案1】:

我也遇到了同样的问题。

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

#if (!DEBUG)

#else //debug code

#endif

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

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

希望对你有帮助

【讨论】:

    【解决方案2】:

    来自MSDN:

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

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

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

    我试过你的代码,看起来还可以。我唯一的区别是对计时器值(Service1.cs)进行硬编码。如果以下方法不起作用,请告诉我。

    Service1.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

    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
        }
    }
    

    我刚刚创建了一个空白的 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);
            }
        }
    }
    

    【讨论】:

    • 我这里有不同的情况。我的 Windows 服务在大多数系统中都可以正常启动。但在少数系统中,我面临错误 1503: 。我尝试了 regedit 解决方案。需要帮助
    【解决方案3】:

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

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

    【讨论】:

    • 这对我有用。我的目标是 4.6,它可以在我的机器上运行,然后去安装一个 Windows Server 2008 机器,它有 4.51 并且没有工作。一旦我将目标更改为 4.51 繁荣!
    • 你拯救了我的一天..好主意。 +1
    • 也是我的问题。谢谢!
    【解决方案4】:

    当我看到这样的问题时,我总是先去查看事件查看器。它确实为初步调查和调试提供了更多重要的细节。

    很多时候,我们忘记了 Event Viewer 会捕获未处理的 .net 运行时异常,这些异常可以在 Windows 日志 > Application 下找到,然后按事件 ID 1026(.NET 运行时)过滤

    【讨论】:

      【解决方案5】:

      构造函数是我的问题。构造函数一定是抛出了关于缺少 DLL 的异常。

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

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

        • 虽然这有助于我在启动服务时绕过问题,但同时也不是解决问题的好方法。
        【解决方案7】:

        我在尝试运行 .Net Core 3.0.0 Windows 服务时遇到了同样的问题。解决方案声明 here 对我有用。但这里是它的要点:

        添加Microsoft.Extensions.Hosting.WindowsServices

        IHostBuilder处添加.UseWindowsService()

        下面是一个示例:

        using Microsoft.Extensions.Hosting;
        
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    IHostEnvironment env = context.HostingEnvironment;
                    config.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
                    config.AddEnvironmentVariables();
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                    config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
                })
                .ConfigureLogging((context, logging) =>
                {
                    logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                    logging.AddConsole();
                    logging.AddDebug();
                })
                .ConfigureServices((context, services) =>
                {                    
                    services.AddHostedService<Worker>();
                })
            .UseWindowsService();
        

        【讨论】:

          【解决方案8】:

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

          【讨论】:

            【解决方案9】:

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

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

            【讨论】:

            • 将配置重命名为 xml 并在默认的 xml 查看器中打开它以检查错误总是一个好主意。
            • 我个人建议从上下文菜单中选择“打开方式”(并确保取消选中“始终使用此应用程序打开”)。从长远来看,可能比来回重命名文件更容易。
            • 我也遇到了配置文件问题。我有额外的" 字符导致了这个问题。
            【解决方案10】:

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

            我将目标服务框架更改为 .Net 4.0。现在可以正常使用了。

            【讨论】:

              【解决方案11】:

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

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

              这是我在创建第一个服务时经过反复试验后发现的。我没有使用VS。我确实使用了 VS 指南(Walkthrough: Creating a Windows Service Application in the Component Designer),而我更愿意使用这个:Creating a C# Service Step-by-Step: Lesson I

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

              【讨论】:

                【解决方案12】:

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

                【讨论】:

                  【解决方案13】:

                  如果您的服务名称与实际的 .exe 文件名不同,请确保您没有与位于同一文件夹中的服务同名的 .exe,因为这会导致它失败。

                  在我的情况下,我有一个名为“Index Reader”的服务指向“Index reader service.exe”,并且在同一个文件夹中有一个名为“Index reader.exe”的exe。删除它可以解决问题。

                  【讨论】:

                    【解决方案14】:

                    我有同样的问题 但就我而言,当我在发布时重建安装程序服务时。 再次安装服务并运行, 该服务开始运行没有任何问题

                    【讨论】:

                      猜你喜欢
                      • 2011-03-28
                      • 2014-08-05
                      • 2011-01-05
                      • 2011-12-29
                      • 2011-04-13
                      • 2015-12-28
                      • 1970-01-01
                      • 2016-03-22
                      相关资源
                      最近更新 更多