【问题标题】:Error 1053 when starting a Windows Service (exe created in Visual Studio)启动 Windows 服务时出现错误 1053(在 Visual Studio 中创建的 exe)
【发布时间】:2017-05-10 21:51:10
【问题描述】:

我有一个从 Visual Studio 中的项目创建的可执行文件,我想用它创建一个服务(这样我就可以在不需要控制台窗口的情况下运行它)。我发布项目,并使用以下方法创建 Windows 服务:

sc create MY.SERVICE binpath= "C:\Program Files\Project\serviceProj\myService.exe 

服务按预期显示在 Windows 服务管理器中。但是,每当我尝试启动该服务时,它会在大约 2 秒后失败并给我以下错误:

Windows could not start the MY.SERVICE on Local Computer. 
Error 1053: The service did not respond to the start or control request in a timely fashion. 

我做过的事情:

在 Visual Studio 中从调试更改为发布

以管理员身份运行一切(创建服务、发布项目、启动服务等)。

我还在某处读到过,增加服务管理器等待服务启动的时间可能会起作用。我添加了 Windows 注册表值来做到这一点,但不幸的是它不起作用。

从命令提示符启动服务通常只需 2-3 秒即可启动并开始侦听请求,因此我不确定发生了什么。

感谢任何帮助。

这是我的 Startup.cs 类:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using System.Diagnostics;
using System.IO;
using Serilog;
using System.Linq;

namespace My.Service
{
    public class Startup
    {
        public static void Main(string[] args)
        {
            var exePath = Process.GetCurrentProcess().MainModule.FileName;
            var directoryPath = Path.GetDirectoryName(exePath);

            if (Debugger.IsAttached || args.Contains("--debug"))
            {
                var host = new WebHostBuilder()
                   .CaptureStartupErrors(true)
                   .UseKestrel()
                   .UseUrls("http://localhost:5002")
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .UseIISIntegration()
                   .UseStartup<Startup>()
                   .Build();
                host.Run();
            }
            else
            {
                var host = new WebHostBuilder()
                    .UseKestrel()
                    .UseUrls("http://localhost:5002")
                    .UseContentRoot(directoryPath)
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .Build();
                host.RunAsService();
            }
        }


        public Startup(IHostingEnvironment env)
        {
            //Setup Logger
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Trace()
                .MinimumLevel.Debug()
                .CreateLogger();
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json");
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}");
            });
        }
    }
}

【问题讨论】:

  • 请告诉我们更多关于您的服务的信息。您的 OnStart 事件处理程序应该尽快完成它的工作并退出,而且它肯定应该在 30 秒内完成。您是否在 OnStart 处理程序中执行长时间运行的任务?也许发布一些代码?
  • @STLDeveloper 我没有 OnStart 事件处理程序 - 应该吗?我有一个已添加到原始帖子中的 Startup.cs 类。我以前从未创建过 Windows 服务 - 根据我在网上看到的情况,听起来可以从可执行文件创建 Windows 服务。
  • 是的,很有可能,但它必须遵循一套关于应用程序结构的非常具体的指导方针。
  • 您在网上看到的很可能是在谈论服务包装器,例如 srvany 或 nssm,它们的唯一工作就是运行其他可执行文件。这通常被总结为(有点误导)“将可执行文件作为服务运行”。

标签: c# visual-studio visual-studio-2015 service windows-services


【解决方案1】:

您看到的错误是来自 Windows 的通知,表明您已启动的服务尚未在合理的时间内(30 秒)完成启动。

发生这种情况是因为您将服务的逻辑塞进了应用的公共 Main() 方法中,这不是您想要的 Windows 服务。

Windows 服务包含一些支持该服务的结构。通常在服务的 Main() 中发生的所有事情都是加载服务,而不是实际启动它运行。该服务包括事件处理程序,以支持响应标准服务操作,例如启动、停止、暂停、继续,以及系统关闭时的处理。

所有 Windows 服务都有的这种结构有点复杂,必须按照操作系统的规范构建。虽然可以手动构建 Windows 服务,但要正确完成所有管道可能很困难,因此让 Visual Studio 帮助您更容易。

在构建 Windows 服务时,最简单直接的方法是让 VS 为您创建新的 Visual Studio 项目时创建一个 Windows 服务项目。新项目将包括您从一开始就需要的所有必要管道和服务功能。

当然,您可以手动构建服务,但实际上没有理由这样做。如果您确实想走手动构建的路径,您至少需要执行以下操作(一个警告 - 我是从内存中执行此操作的,并且不久前我移到了 VS 2017,所以这可能不完全正确):

  • 将 Windows 服务组件添加到您的项目中。为此,请在解决方案资源管理器中右键单击您的项目并选择“添加”。在出现的菜单中,选择“组件...”。在出现的对话框中,选择“Windows 服务”。提个建议,在按下“添加”按钮之前给文件起一个有意义的名称。

  • 添加 Windows 服务组件后,右键单击它并设置其属性。

  • 要对 OnStart、OnStop、OnPause、OnContinue 和 OnShutdown 事件处理程序进行编程,请右键单击 Windows 服务设计空间(或右键单击解决方案资源管理器中的文件)并选择“查看代码”。

关于构建 Windows 服务的知识还有很多,这里就不一一列举了。我建议在你在这个领域做很多事情之前找到一些关于这个主题的好的文档并研究它,因为在这里做错事会对运行你的服务的机器产生相当大的影响。看看MSDN: Walkthrough: Creating a Windows Service Application in the Component Designer。它应该有助于更彻底地解释这一点。

【讨论】:

    【解决方案2】:

    所以我打开了事件查看器以获取有关我收到的错误的更多信息。我收到导致错误的 FileNotFoundException。这让我感到惊讶,因为从 Visual Studio 或命令行运行该服务可以正常工作 - 可以找到该文件。有问题的文件位于工作目录中。我将文件的路径(而不是使用相对路径)硬编码到我的 File.OpenText 方法中并且它起作用了。因此,由于某种原因,相对路径不适用于 Windows 服务。

    【讨论】:

    • 这里也一样 - 发生了错误,而不是报告,Windows 立即声明有超时。我在这里说你好世界。剥离了我的日志记录代码,所以我只有服务存根,一切正常 - 甚至调试构建。
    • 您在哪里找到带有 FileNotFoundException 的日志?我正在查看事件查看器,我只能看到“由于以下错误,无法启动 MyService:服务未在预期时间内响应启动信号或控制信号。”
    【解决方案3】:

    尝试修复.SetBasePath(env.ContentRootPath): https://github.com/dasMulli/dotnet-win32-service/issues/54

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      相关资源
      最近更新 更多