将Windows服务作为控制台应用程序运行
我想调试一个Windows服务,但它弹出一条错误消息说
无法从命令行或调试器启动服务。 必须使用installutil.exe安装Windows服务,然后使用Server explorer,Windows服务管理工具或NET启动命令启动。
我真的不知道这个错误…..
在运行Windows服务之前,必须首先使用installutil“安装”它。 例如:
C:\installutil -ic:\path\to\project\debug\service.exe
然后,您可以打开服务列表以启动它。 例如:
- 右键点击“我的电脑”
- 点击“管理”
- 打开’服务和应用’
- 点击“服务”
- 在列表中找到您的服务,然后右键单击它
- 点击“开始”
一旦启动,您可以进入Visual Studio,单击“Debug”,然后单击“Attach to Process”。
另一种方法是将此行添加到服务中的OnStart()方法:
System.Diagnostics.Debugger.Launch();
当你这样做时,它会提示你选择一个Visual Studio实例来调试服务。
您可以根据您是处于DEBUG模式(通常在Visual Studio内部但不一定是)或RELEASE模式(当它在生产中作为服务运行时)来更改程序集的启动模式:
改变这个:
static class Program { static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); } }
对此:
static class Program { static void Main() { #if(!DEBUG) ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); #else MyService myServ = new MyService(); myServ.Process(); // here Process is my Service function // that will run when my service onstart is call // you need to call your own method or function name here instead of Process(); #endif } }
该技术取自本文 ,该文章的作者Tejas Vaishnav负责。 我在这里复制了代码片段,因为SO赞成完整的答案而不是可能在某个时间消失的链接。
请检查您是否处于“DEBUG”或“RELEASE”模式。 当我尝试在“RELEASE”模式下调试服务时出现此错误。 当我把它改为“DEBUG”时,一切正常。
这是在您按照上面其他人的建议正确安装服务之后。
要防止发生此错误并允许服务在通常的服务控制器之外运行,您可以检查Environment.UserInteractive
标志。 如果已设置,则可以使用输出运行服务到控制台,而不是让它运行到返回该错误的ServiceBase代码。
在使用ServiceBase运行服务的代码之前,将其添加到Program.Main()的开头:
if (Environment.UserInteractive) { var service = new WindowsService(); service.TestInConsole(args); return; }
由于OnStart和OnStop方法在您的服务中protected
,您需要向该类添加另一个方法,您可以从Main()运行并为您调用这些方法,例如:
public void TestInConsole(string[] args) { Console.WriteLine($"Service starting..."); this.OnStart(args); Console.WriteLine($"Service started. Press any key to stop."); Console.ReadKey(); Console.WriteLine($"Service stopping..."); this.OnStop(); Console.WriteLine($"Service stopped. Closing in 5 seconds."); System.Threading.Thread.Sleep(5000); }
最后,确保输出是项目属性中的控制台应用程序。
您现在可以像任何其他服务器一样运行服务可执行文件,它将作为控制台启动。 如果从Visual Studio启动它,调试器将自动附加。 如果您注册并将其作为服务启动,它将作为服务正常运行而无需任何更改。
我发现的唯一区别是,当作为控制台应用程序运行时,代码不会写入事件日志,您可能希望输出通常记录到控制台的任何内容。
此服务调试技术是docs.microsoft.com上解释的技术之一