【问题标题】:Debugging A Window System Service in C#在 C# 中调试窗口系统服务
【发布时间】:2011-11-16 19:03:23
【问题描述】:

我收到错误“无法从命令行或调试器启动服务。必须首先安装 Windows 服务(使用 installutil.exe),然后使用 ServerExplorer、Windows 服务管理工具或 NET START 命令启动。

那么,有没有办法在不安装 Windows 服务的情况下运行或测试它?我应该在控制台应用程序中构建我的项目,然后在测试后将代码转移到 Windows Server 项目中吗?

谢谢。

【问题讨论】:

    标签: c# debugging service


    【解决方案1】:

    我倾向于向我的服务类添加一个静态 Main 方法,以便它可以作为控制台应用程序调用以进行调试,但也可以作为服务安装和运行。

    类似于以下内容:

        public partial class ControllerService : ServiceBase
        {
    
            static void Main(string[] args)
            {
                ControllerService service = new ControllerService();
    
                cmdLine = CommandLineParser.Parse(args);
    
                if (Environment.UserInteractive)
                {
                    switch (cmdLine.StartMode)
                    {
                        case StartMode.Install:
                            //Service Install Code Here
                            break;
                        case StartMode.Uninstall:
                            //Service Uninstall Code Here
                            break;
                        case StartMode.Console:
                        default:
                            service.OnStart(args);
                            consoleCloseEvent.WaitOne();
                            break;
                    }
                }
                else
                {
                    ServiceBase.Run(service);
                }
            }
    
            protected override void OnStart(string[] args)
            {
                 //Do Start Stuff Here
            }
    
            protected override void OnStop()
            {
                if (Environment.UserInteractive)
                {
                    consoleCloseEvent.Set();
                }
            }
       }
    

    【讨论】:

    • 我觉得我得试试这个方法,看起来比我现在用的好多了
    • @gwhitake 您将如何访问服务。由于其保护级别,Onstart 无法访问。
    • @ClearLogic - service.OnStart() 是可访问的,因为您是从服务类内部调用它。
    【解决方案2】:

    您可以尝试将执行实际工作的代码保留在单独的程序集中,并从服务或控制台应用程序中调用该代码进行测试。

    【讨论】:

      【解决方案3】:

      您可以使用两种方法。

      1. 创建单独的 windows 窗体应用程序并从 windows 窗体项目中调用该代码。

      2. 在调用方法中,请使用:

         #if Debug
         Debugger.Launch()
         #endif
        

      我希望它有所帮助。

      【讨论】:

        猜你喜欢
        • 2011-10-23
        • 2016-12-29
        • 1970-01-01
        • 2016-03-26
        • 1970-01-01
        • 2011-07-27
        • 1970-01-01
        • 1970-01-01
        • 2017-12-02
        相关资源
        最近更新 更多