如何从visual studio运行(F5)Windows服务

dot*_*der 30 testing debugging unit-testing windows-services visual-studio

如何从visual studio运行Windows服务项目.

我正在visual studio 2008中构建一个windows serivce,我必须始终从控制面板运行该服务,然后将调试器连接到正在运行的服务实例.它有点烦人,因为我清理了很多代码,需要在开发过程中多次重启我的服务.

我想设置我的项目,以便能够点击F5并运行服务并直接进入调试模式.关于如何实现这一目标的一些提示会很棒.

提前致谢!!!

Mat*_*vis 28

这里复制.

static void Main(string[] args)  
{  
    DemoService service = new DemoService();  

    if (Environment.UserInteractive)  
    {  
        service.OnStart(args);  
        Console.WriteLine("Press any key to stop program");  
        Console.Read();  
        service.OnStop();  
    }  
    else 
    {  
        ServiceBase.Run(service);  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

这应该允许您从Visual Studio中运行.

另一种方法是通过调用在代码中嵌入一个程序断点System.Diagnostics.Debugger.Break().当您将其放入服务的OnStart()回调并从服务控制台启动服务时,程序断点将触发一个对话框,允许您附加到Visual Studio的现有实例或启动新的实例.这实际上是我用来调试我的服务的机制.

  • 该链接的说明对我来说非常合适.谢谢! (3认同)

Sam*_*eff 7

在您的Main()例行检查中Debugger.IsAttached,如果它是真的启动您的应用程序,就好像它是一个控制台,如果没有,请打电话ServiceBase.Run().


Rya*_*ohn 6

可以为 Windows 服务设置一个配套项目,该项目作为控制台应用程序运行,但使用反射访问服务方法。有关详细信息和示例,请参阅此处:http://ryan.kohn.ca/articles/how-to-debug-a-windows-service-in-csharp-using-reflection/

以下是您在控制台应用程序中需要的相关代码:

using System;
using System.Reflection;

namespace TestableWindowsService
{
  class TestProgram
  {
    static void Main()
    {
      Service1 service = new Service1();

      Type service1Type = typeof (Service1);

      MethodInfo onStart = service1Type.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Instance); //retrieve the OnStart method so it can be called from here

      onStart.Invoke(service, new object[] {null}); //call the OnStart method
    }
  }
}
Run Code Online (Sandbox Code Playgroud)