是否有更简单的方法来单步执行代码,而不是经过Windows服务控制管理器启动服务,而后将调试器附加到线程? 这有点麻烦,我想知道是否有一个更简单的方法。 工具
几周前,当我找到一个新的服务项目时,我找到了这个帖子。 虽然有不少很棒的建议,但我仍然没有找到我想要的解决方案:能够在OnStop
服务类进行任何修改的状况下调用服务类的OnStart
和OnStop
方法。 spa
我提出的解决方案使用Environment.Interactive
选择运行模式,正如此帖的其余答案所示。 操作系统
static void Main() { ServiceBase[] servicesToRun; servicesToRun = new ServiceBase[] { new MyService() }; if (Environment.UserInteractive) { RunInteractive(servicesToRun); } else { ServiceBase.Run(servicesToRun); } }
RunInteractive
助手使用反射来调用受保护的OnStart
和OnStop
方法: 命令行
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); }
这是所需的全部代码,但我还编写了演练解释。 线程
您还能够经过命令提示符(sc.exe)启动该服务。 调试
就我的而言,我会在调试阶段将代码做为独立程序运行,而且当大多数错误被解决时,将更改成做为服务运行。 code
我之前作的是有一个命令行开关,它能够做为服务或常规应用程序启动程序。 而后,在个人IDE中,我会设置开关,以便我能够单步执行代码。 进程
使用某些语言,您实际上能够检测它是否在IDE中运行,并自动执行此切换。 get
你用的是什么语言? string
我一般作的是将服务的逻辑封装在一个单独的类中,并从“runner”类开始。 此运行器类能够是实际服务,也能够只是控制台应用程序。 因此你的解决方案有(至少)3个项目:
/ConsoleRunner /.... /ServiceRunner /.... /ApplicationLogic /....
我认为这取决于您使用的操做系统,由于会话之间的分离,Vista很难链接到服务。
我过去使用的两个选项是:
但愿这能够帮助。