zoukankan      html  css  js  c++  java
  • an easy way to debug windows service in .net

    Introduction

    Normally debugging a windows service under Visual Studio .Net is painful.  Windows services won't actually run directly within Visual Studio .Net, so the usual technique is to install and start the windows service and then attach a debugger to it.  An alternative approach is to pull the guts out of the service, stick it in a separate library and then build some other app (e.g. a console app) to sit in front of it.  This approach uses neither of those techniques.

    When building a C# Windows Service project in Visual Studio it will leave you with a class containing quite a few methods including a Main(), such as this:

    // The main entry point for the process
    static void Main()
    {
        System.ServiceProcess.ServiceBase[] ServicesToRun;
    
        // More than one user Service may run within the same process. To add
        // another service to this process, change the following line to
        // create a second service object. For example,
        //
        // ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
        //
    
        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
        System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    }

    Obviously its the Main() above that ends up executing the service, and it's the Main() that this approach manipulates so that the Windows Service can be debugged directly within Visual Studio .Net

    Using the example above (and removing some of the comments) here's how:

    // The main entry point for the process
    static void Main()
    {
    #if (!DEBUG)
        System.ServiceProcess.ServiceBase[] ServicesToRun;
        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
        System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    #else
        // debug code: allows the process to run as a non-service
        // will kick off the service start point, but never kill it
        // shut down the debugger to exit
        Service1 service = new Service1();
        service.<Your Service's Primary Method Here>();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    #endif 
    }

    It's crude, but effective (CBE).  Run the service in debug mode to debug it, compile and install it as a release build and it's a full and proper windows service.

    ref

    http://www.codeproject.com/useritems/DebugWinServices.asp

  • 相关阅读:
    快手记录的面试题2
    快手Java实习一二面经(记录的面试题1)
    219. 存在重复元素 II(面试题也考过)
    117. 填充每个节点的下一个右侧节点指针 II(没想到,但是其实蛮简单的)
    116. 填充每个节点的下一个右侧节点指针
    最后来几个快手的面试题吧,先记录下来大概看看
    快手Java实习一二面面经(转载)
    双亲委派模型
    聚集索引与非聚集索引总结(转载)
    136. 只出现一次的数字
  • 原文地址:https://www.cnblogs.com/margiex/p/140384.html
Copyright © 2011-2022 走看看