调试c#中的窗口系统服务

本文关键字:窗口 系统服务 调试 | 更新日期: 2023-09-27 18:15:07

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

那么,有没有一种方法可以运行或测试Windows服务而不安装它?我是否应该在控制台应用程序中构建我的项目,然后在测试后将代码转移到Windows Server项目?

谢谢。

调试c#中的窗口系统服务

我倾向于在我的服务类中添加一个静态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();
            }
        }
   }

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

有两种方法可以使用。

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

  2. 呼叫方式,请使用:

     #if Debug
     Debugger.Launch()
     #endif
    

我希望它有帮助。