是否有比通过Windows服务控制管理器启动服务,然后将调试器附加到线程更简单的方法来逐步遍历代码?这有点麻烦,我想知道是否有更直接的方法。


当前回答

这段YouTube视频由Fabio Scopel解释了如何调试一个Windows服务相当好…实际的方法从视频中的4:45开始…

下面是视频中解释的代码…在你的Program.cs文件中,添加Debug部分的东西…

namespace YourNamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
#if DEBUG
            Service1 myService = new Service1();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
#endif

        }
    }
}

在你的Service1.cs文件中,添加OnDebug()方法…

    public Service1()
    {
        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    protected override void OnStart(string[] args)
    {
        // your code to do something
    }

    protected override void OnStop()
    {
    }

它是如何工作的

基本上,你必须创建一个公共void OnDebug(),调用OnStart(string[] args),因为它是受保护的,不能在外部访问。void Main()程序添加了#if预处理器和#DEBUG。

如果项目在DEBUG模式下编译,Visual Studio定义DEBUG。这将允许调试部分(下面)在条件为真时执行

Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

它将像控制台应用程序一样运行,一旦一切顺利,您可以更改模式Release和常规else部分将触发逻辑

其他回答

如果我想快速调试服务,我只需在那里放入一个Debugger.Break()。当到达这条线时,它会将我拉回到VS.当你完成时,不要忘记删除这条线。

更新:作为#if DEBUG pragmas的替代,你也可以使用Conditional("DEBUG_SERVICE")属性。

[Conditional("DEBUG_SERVICE")]
private static void DebugMode()
{
    Debugger.Break();
}

在OnStart上,只需调用这个方法:

public override void OnStart()
{
     DebugMode();
     /* ... do the rest */
}

在那里,代码将只在调试构建期间启用。在此过程中,为服务调试创建一个单独的Build Configuration可能会很有用。


static void Main()
{
#if DEBUG
                // Run as interactive exe in debug mode to allow easy
                // debugging.

                var service = new MyService();
                service.OnStart(null);

                // Sleep the main thread indefinitely while the service code
                // runs in .OnStart

                Thread.Sleep(Timeout.Infinite);
#else
                // Run normally as service in release mode.

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]{ new MyService() };
                ServiceBase.Run(ServicesToRun);
#endif
}

当我写一个服务时,我把所有的服务逻辑都放在一个dll项目中,并创建了两个“主机”来调用这个dll,一个是Windows服务,另一个是命令行应用程序。

我使用命令行应用程序进行调试,并仅针对无法在命令行应用程序中重现的错误将调试器附加到实际服务。

如果您使用这种方法,请记住,您必须在实际服务中运行时测试所有代码,而命令行工具是一个很好的调试辅助工具,它是一个不同的环境,并且它的行为与实际服务不完全相同。

第一行的Debugger.Break()怎么样?

对于常规的小程序,我做了一个非常简单的技巧来轻松调试我的服务:

在服务启动时,我检查命令行参数“/debug”。如果使用此参数调用服务,我不会执行通常的服务启动,而是启动所有侦听器,并只显示一个消息框“调试正在进行中,按ok结束”。

因此,如果我的服务以通常的方式启动,它将作为服务启动,如果它以命令行参数/调试启动,它将像正常程序一样工作。

在VS中,我将添加/debug作为调试参数,并直接启动服务程序。

通过这种方式,我可以轻松地调试大多数小型问题。当然,有些东西仍然需要作为服务进行调试,但对于99%来说,这已经足够了。