【问题标题】:How do I debug Windows services in Visual Studio?如何在 Visual Studio 中调试 Windows 服务?
【发布时间】:2011-06-08 09:46:25
【问题描述】:

是否可以在 Visual Studio 中调试 Windows 服务?

我使用了类似的代码

System.Diagnostics.Debugger.Break();

但它给出了一些代码错误,例如:

我收到两个事件错误:eventID 4096 VsJITDebugger 和“服务没有 不响应启动或控制 及时提出要求。”

【问题讨论】:

    标签: c# visual-studio visual-studio-2010 windows-services


    【解决方案1】:

    你应该把所有做的代码从服务项目中分离出来,放到一个单独的项目中,然后制作一个你可以正常运行和调试的测试应用程序。

    服务项目只是实现它的服务部分所需的外壳。

    【讨论】:

    • 哇!! ctrl+C 然后 ctrl+V,我的意思是新建项目。是的,只有我在做。是否可以将任何进程附加到调试或任何其他选项而不是单独的项目。?
    • 当然可以,但是如果在开发的时候把服务部分去掉的话,开发windows服务会容易很多。
    • hmmm...这是一个好方法,但它只是使工作加倍。我认为任何其他方式都会存在。
    • 我看不出它会如何“加倍”工作。当然,在制作额外项目并将服务中的代码分离到第三个项目时会增加一点开销,但除此之外,您不会复制代码,而是移动它,并引用该项目。
    • ^+1。它使管理服务的工作加倍,这在开发时间方面几乎为零,而且你只做一次。调试一个服务是痛苦的 - 而是让它作为命令行双重启动。检查谷歌是否允许这样做的预定义包装类(他们使用反射来模拟启动/停止服务类)。一小时的工作,大量的储蓄,净损失:负数 - 你赢得了时间。
    【解决方案2】:

    要么按照 Lasse V. Karlsen 的建议,要么在您的服务中设置一个循环,等待调试器附加。最简单的是

    while (!Debugger.IsAttached)
    {
        Thread.Sleep(1000);
    }
    
    ... continue with code
    

    这样您就可以启动服务并在 Visual Studio 中选择“附加到进程...”并附加到您的服务,然后将恢复正常执行。

    【讨论】:

    • 我应该把上面的代码放在哪里......并且在附加过程中我得到了我的服务,名为 disable
    • 我们也使用了这样的代码if (Environment.UserInteractive) { InteractiveRun(args); } else { Service instance = new Service(); ServiceBase[] servicesToRun = new ServiceBase[] { instance }; ServiceBase.Run(servicesToRun); }
    • 该代码应该尽早在您想要调试的任何代码能够运行之前。
    • @Pawan: 在Start/OnStart() 我猜
    • @Kirill:使用波浪线突出显示 cmets 中的代码,例如foo(bar)
    【解决方案3】:

    您可以制作控制台应用程序。我用这个main函数:

        static void Main(string[] args)
        {
            ImportFileService ws = new ImportFileService();
            ws.OnStart(args);
            while (true)
            {
                ConsoleKeyInfo key = System.Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                    break;
            }
            ws.OnStop();
        }
    

    我的 ImportFileService 类与我的 Windows 服务应用程序中的类完全相同,除了继承者 (ServiceBase)。

    【讨论】:

    • 是在同一个项目上还是我在这个控制台应用程序的另一个项目上
    • 这是 2 个具有相似类的不同项目。就我而言,这是一个简单的服务,只有 ImportFileService 类是重复的。当我想开发/测试时,我使用控制台应用程序,然后复制/粘贴。就像 Lasse V. Karlsen 说的,它是一个调试程序,所有的逻辑(业务)都在第三个项目上。
    • 是的,是的。这就是为什么我说“除了继承人(ServiceBase)。”。我发现在控制台应用程序中调试更容易,但我理解这是否不能说服所有人。
    【解决方案4】:

    你也可以试试这个。

    1. 创建您的 Windows 服务并安装并启动...。也就是说,Windows 服务必须在您的系统中运行。
    2. 当您的服务正在运行时,进入 Debug 菜单,点击 Attach Process(或旧版 Visual Studio 中的进程)
    3. 找到您正在运行的服务,然后确保选中显示所有用户的进程和显示所有会话中的进程,如果没有则选中它。

    1. 点击附加按钮
    2. 点击确定
    3. 点击关闭
    4. 在您想要的位置设置一个断点并等待执行。只要您的代码达到该点,它就会自动调试。
    5. 记住,把你的断点放在可到达的地方,如果是onStart(),则停止并重新启动服务

    (经过大量谷歌搜索,我在“如何在 Visual Studio 中调试 Windows 服务”中找到了这一点。)

    【讨论】:

    • 在 VS2013 Update 5 中看不到这个选项。:(
    • 但是你需要以管理员身份运行你的 Vs-2017
    • 我试过这个。它在 onStop 中使用断点,但在 onStart 上没有,因为当服务停止时,调试器会被取消连接
    【解决方案5】:

    不幸的是,如果您试图在 Windows 服务操作的一开始就调试某些东西,那么“附加”到正在运行的进程将不起作用。我尝试在 OnStart 过程中使用 Debugger.Break(),但对于 64 位 Visual Studio 2010 编译的应用程序,break 命令只会引发如下错误:

    System error 1067 has occurred.
    

    此时,您需要在注册表中为可执行文件设置“图像文件执行”选项。设置需要五分钟,而且效果很好。这是一篇 Microsoft 文章,详细信息如下:

    How to: Launch the Debugger Automatically

    【讨论】:

      【解决方案6】:

      您也可以尝试 System.Diagnostics.Debugger.Launch() 方法。它有助于将调试器指针指向指定位置,然后您可以调试代码。

      在此步骤之前请安装您的 service.exe 使用 Visual Studio 命令提示符的命令行 - installutil projectservice.exe

      然后从控制面板 -> 管理工具 -> 计算机管理 -> 服务和应用程序 -> 服务 -> 您的服务名称开始您的服务

      【讨论】:

        【解决方案7】:

        鉴于ServiceBase.OnStart 具有protected 可见性,我沿着反射路线进行调试。

        private static void Main(string[] args)
        {
            var serviceBases = new ServiceBase[] {new Service() /* ... */ };
        
        #if DEBUG
            if (Environment.UserInteractive)
            {
                const BindingFlags bindingFlags =
                    BindingFlags.Instance | BindingFlags.NonPublic;
        
                foreach (var serviceBase in serviceBases)
                {
                    var serviceType = serviceBase.GetType();
                    var methodInfo = serviceType.GetMethod("OnStart", bindingFlags);
        
                    new Thread(service => methodInfo.Invoke(service, new object[] {args})).Start(serviceBase);
                }
        
                return;
            }
        #endif
        
            ServiceBase.Run(serviceBases);
        }
        

        请注意,Thread 默认情况下是前台线程。 returning from Main 在假服务线程运行时不会终止进程。

        【讨论】:

        • 由于 OnStart 应该快速返回,您不需要在另一个线程中执行此操作。但是,如果服务没有启动另一个线程,您的进程将立即退出。
        • @MattConnolly 关于后者:如有必要,我更改上面的代码以启动一个永远休眠的前台线程(在正常处理之前)。
        • 这应该是一个真实的答案。效果很好!
        【解决方案8】:

        我刚刚将此代码添加到我的服务类中,因此我可以间接调用 OnStart,类似于 OnStop。

            public void MyOnStart(string[] args)
            {
                OnStart(args);
            }
        

        【讨论】:

          【解决方案9】:

          在服务OnStart方法中使用以下代码:

          System.Diagnostics.Debugger.Launch();
          

          从弹出消息中选择 Visual Studio 选项。

          注意:要仅在调试模式下使用它,可以使用#if DEBUG 编译器指令,如下所示。这将防止在生产服务器上的发布模式下发生意外或调试。

          #if DEBUG
              System.Diagnostics.Debugger.Launch();
          #endif
          

          【讨论】:

          • 记得以管理员身份运行 VS。然后它将在列表中可用。
          • 有人可以澄清弹出消息的含义吗?何时/如何出现?
          • @Mike,安装并启动服务,它就会出现。
          • @Mike,它是一个 Windows 对话框,会在交互式(登录)桌面上弹出并询问您是否要选择一个应用程序来调试进程。如果您选择 VS,它将启动调试器并附加到进程
          【解决方案10】:

          我在 Visual Studio 项目中使用/Console 参数调试 → 启动选项 → 命令行参数:

          public static class Program
          {
              [STAThread]
              public static void Main(string[] args)
              {
                   var runMode = args.Contains(@"/Console")
                       ? WindowsService.RunMode.Console
                       : WindowsService.RunMode.WindowsService;
                   new WinodwsService().Run(runMode);
              }
          }
          
          
          public class WindowsService : ServiceBase
          {
              public enum RunMode
              {
                  Console,
                  WindowsService
              }
          
              public void Run(RunMode runMode)
              {
                  if (runMode.Equals(RunMode.Console))
                  {
                      this.StartService();
                      Console.WriteLine("Press <ENTER> to stop service...");
                      Console.ReadLine();
          
                      this.StopService();
                      Console.WriteLine("Press <ENTER> to exit.");
                      Console.ReadLine();
                  }
                  else if (runMode.Equals(RunMode.WindowsService))
                  {
                      ServiceBase.Run(new[] { this });
                  }
              }
          
              protected override void OnStart(string[] args)
              {
                  StartService(args);
              }
          
              protected override void OnStop()
              {
                  StopService();
              }
          
              /// <summary>
              /// Logic to Start Service
              /// Public accessibility for running as a console application in Visual Studio debugging experience
              /// </summary>
              public virtual void StartService(params string[] args){ ... }
          
              /// <summary>
              /// Logic to Stop Service
              /// Public accessibility for running as a console application in Visual Studio debugging experience
              /// </summary>
              public virtual void StopService() {....}
          }
          

          【讨论】:

            【解决方案11】:

            在OnStart 方法中,执行以下操作。

            protected override void OnStart(string[] args)
            {
                try
                {
                    RequestAdditionalTime(600000);
                    System.Diagnostics.Debugger.Launch(); // Put breakpoint here.
            
                    .... Your code
                }
                catch (Exception ex)
                {
                    .... Your exception code
                }
            }
            

            然后以管理员身份运行命令提示符并输入以下内容:

            c:\> sc create test-xyzService binPath= <ProjectPath>\bin\debug\service.exe type= own start= demand
            

            以上行将在服务列表中创建 test-xyzService。

            要启动服务,这将提示您是否附加到 Visual Studio 中首次亮相。

            c:\> sc start text-xyzService
            

            停止服务:

            c:\> sc stop test-xyzService
            

            删除或卸载:

            c:\> sc delete text-xyzService
            

            【讨论】:

              【解决方案12】:

              试试 Visual Studio 自己的构建后事件命令行。

              尝试在构建后添加这个:

              @echo off
              sc query "ServiceName" > nul
              if errorlevel 1060 goto install
              goto stop
              
              :delete
              echo delete
              sc delete "ServiceName" > nul
              echo %errorlevel%
              goto install
              
              :install
              echo install
              sc create "ServiceName" displayname= "Service Display Name" binpath= "$(TargetPath)" start= auto > nul
              echo %errorlevel%
              goto start
              
              :start
              echo start
              sc start "ServiceName" > nul
              echo %errorlevel%
              goto end
              
              :stop
              echo stop
              sc stop "ServiceName" > nul
              echo %errorlevel%
              goto delete
              
              :end
              

              如果构建错误带有类似Error 1 The command "@echo off sc query "ServiceName" &gt; nul 这样的消息,Ctrl + C 然后 Ctrl + V kbd> 将错误信息写入记事本,查看信息的最后一句。

              可能是exited with code x。在这里查找一些常见错误中的代码,看看如何解决它。

              1072 -- Marked for deletion → Close all applications that maybe using the service including services.msc and Windows event log.
              1058 -- Can't be started because disabled or has no enabled associated devices → just delete it.
              1060 -- Doesn't exist → just delete it.
              1062 -- Has not been started → just delete it.
              1053 -- Didn't respond to start or control → see event log (if logged to event log). It may be the service itself throwing an exception.
              1056 -- Service is already running → stop the service, and then delete.
              

              更多关于错误代码here。

              如果生成错误并带有这样的消息,

              Error    11    Could not copy "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". Exceeded retry count of 10. Failed.    ServiceName
              Error    12    Unable to copy file "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". The process cannot access the file 'bin\Debug\ServiceName.exe' because it is being used by another process.    ServiceName
              

              打开cmd,然后尝试先用taskkill /fi "services eq ServiceName" /f杀死它

              如果一切正常,F5 应该足以调试它。

              【讨论】:

                【解决方案13】:

                一篇 Microsoft 文章解释了如何调试 Windows 服务 here,以及如果通过附加到进程进行调试,任何人都可能会错过哪些部分。

                以下是我的工作代码。我遵循了微软建议的方法。

                将此代码添加到program.cs:

                static void Main(string[] args)
                {
                    // 'If' block will execute when launched through Visual Studio
                    if (Environment.UserInteractive)
                    {
                        ServiceMonitor serviceRequest = new ServiceMonitor();
                        serviceRequest.TestOnStartAndOnStop(args);
                    }
                    else // This block will execute when code is compiled as a Windows application
                    {
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[]
                        {
                            new ServiceMonitor()
                        };
                        ServiceBase.Run(ServicesToRun);
                    }
                }
                

                将此代码添加到 ServiceMonitor 类。

                internal void TestOnStartAndOnStop(string[] args)
                {
                    this.OnStart(args);
                    Console.ReadLine();
                    this.OnStop();
                }
                

                现在转到项目属性,选择选项卡“应用程序”并在调试时选择输出类型为“控制台应用程序”,或在完成调试时选择“Windows应用程序”,重新编译并安装您的服务。

                【讨论】:

                • 有没有办法在 Debug 和 Window Application 中设置输出到控制台应用程序?
                【解决方案14】:

                我找到了这个问题,但我认为缺少一个清晰简单的答案。

                我不想将调试器附加到进程,但我仍然希望能够调用服务OnStart 和OnStop 方法。我还希望它作为控制台应用程序运行,以便我可以将来自NLog 的信息记录到控制台。

                我发现了这些出色的指南:

                首先将项目 Output type 更改为 Console Application。

                将您的 Program.cs 更改为如下所示:

                static class Program
                {
                    /// <summary>
                    /// The main entry point for the application.
                    /// </summary>
                    static void Main()
                    {
                        // Startup as service.
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[]
                        {
                            new Service1()
                        };
                
                        if (Environment.UserInteractive)
                        {
                            RunInteractive(ServicesToRun);
                        }
                        else
                        {
                            ServiceBase.Run(ServicesToRun);
                        }
                    }
                }
                

                然后添加以下方法,让服务以交互模式运行。

                static void RunInteractive(ServiceBase[] servicesToRun)
                {
                    Console.WriteLine("Services running in interactive mode.");
                    Console.WriteLine();
                
                    MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
                        BindingFlags.Instance | BindingFlags.NonPublic);
                    foreach (ServiceBase service in servicesToRun)
                    {
                        Console.Write("Starting {0}...", service.ServiceName);
                        onStartMethod.Invoke(service, new object[] { new string[] { } });
                        Console.Write("Started");
                    }
                
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine(
                        "Press any key to stop the services and end the process...");
                    Console.ReadKey();
                    Console.WriteLine();
                
                    MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
                        BindingFlags.Instance | BindingFlags.NonPublic);
                    foreach (ServiceBase service in servicesToRun)
                    {
                        Console.Write("Stopping {0}...", service.ServiceName);
                        onStopMethod.Invoke(service, null);
                        Console.WriteLine("Stopped");
                    }
                
                    Console.WriteLine("All services stopped.");
                    // Keep the console alive for a second to allow the user to see the message.
                    Thread.Sleep(1000);
                }
                

                【讨论】:

                • 很棒的代码!简单,有效。 +1。但同样简单,我把它做成了一个 Forms 应用程序。我真的很讨厌控制台应用程序。此外,您可以轻松地为每个服务事件实现一个表单按钮。
                【解决方案15】:

                通过 http 调试 Windows 服务(使用 VS 2015 Update 3 和 .Net FW 4.6 测试)

                首先,您必须在 VS 解决方案中创建一个控制台项目(添加 -> 新项目 -> 控制台应用程序)。

                在新项目中,使用该代码创建一个“ConsoleHost”类:

                class ConsoleHost : IDisposable
                {
                    public static Uri BaseAddress = new Uri(http://localhost:8161/MyService/mex);
                    private ServiceHost host;
                
                    public void Start(Uri baseAddress)
                    {
                        if (host != null) return;
                
                        host = new ServiceHost(typeof(MyService), baseAddress ?? BaseAddress);
                
                        //binding
                        var binding = new BasicHttpBinding()
                        {
                            Name = "MyService",
                            MessageEncoding = WSMessageEncoding.Text,
                            TextEncoding = Encoding.UTF8,
                            MaxBufferPoolSize = 2147483647,
                            MaxBufferSize = 2147483647,
                            MaxReceivedMessageSize = 2147483647
                        };
                
                        host.Description.Endpoints.Clear();
                        host.AddServiceEndpoint(typeof(IMyService), binding, baseAddress ?? BaseAddress);
                
                        // Enable metadata publishing.
                        var smb = new ServiceMetadataBehavior
                        {
                            HttpGetEnabled = true,
                            MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 },
                        };
                
                        host.Description.Behaviors.Add(smb);
                
                        var defaultBehaviour = host.Description.Behaviors.OfType<ServiceDebugBehavior>().FirstOrDefault();
                        if (defaultBehaviour != null)
                        {
                            defaultBehaviour.IncludeExceptionDetailInFaults = true;
                        }
                
                        host.Open();
                    }
                
                    public void Stop()
                    {
                        if (host == null)
                            return;
                
                        host.Close();
                        host = null;
                    }
                
                    public void Dispose()
                    {
                        this.Stop();
                    }
                }
                

                这是 Program.cs 类的代码:

                public static class Program
                {
                    [STAThread]
                    public static void Main(string[] args)
                    {
                        var baseAddress = new Uri(http://localhost:8161/MyService);
                        var host = new ConsoleHost();
                        host.Start(null);
                        Console.WriteLine("The service is ready at {0}", baseAddress);
                        Console.WriteLine("Press <Enter> to stop the service.");
                        Console.ReadLine();
                        host.Stop();
                    }
                }
                

                connectionstrings等配置应该复制到Console项目的App.config文件中。

                要启动控制台,请右键单击控制台项目,然后单击调试 -> 启动新实例。

                【讨论】:

                  【解决方案16】:

                  我使用了一个很棒的 Nuget 包,名为 ServiceProcess.Helpers。

                  我引用...

                  它通过在附加调试器运行时创建播放/停止/暂停 UI 来帮助调试 Windows 服务,但也允许在 Windows 服务器环境中安装和运行服务。

                  这一切只需一行代码。

                  http://windowsservicehelper.codeplex.com/

                  安装并连接后,您只需将 Windows 服务项目设置为启动项目,然后单击调试器上的启动。

                  【讨论】:

                  • 感谢分享!这是迄今为止最简单的解决方案!
                  【解决方案17】:

                  只需将一个构造函数添加到您的服务类(如果您还没有的话)。下面,您可以查看 Visual Basic .net 的示例。

                  Public Sub New()
                     OnStart(Nothing) 
                  End Sub
                  

                  之后,右键单击项目并选择“Debug -> Start a new instance”。

                  【讨论】:

                    猜你喜欢
                    • 2018-09-07
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-10-25
                    • 2012-11-04
                    • 2016-04-24
                    相关资源
                    最近更新 更多