使用预处理程序指令#if在Visual Studio中调试WindowsService

时间:2012-04-25 07:37:32

标签: c# visual-studio-2010 debugging windows-services

当我使用VS2010 SP1时,我编写了一个Windows服务。现在我想调试它而不安装它。所以我在Program.cs main方法中编写代码如下:

#if (DEBUG)
            ControllerNTService service =new ControllerNTService();
            Console.ReadLine();
#else
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new ControllerNTService() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#endif

我希望在VS 2010中调试Windows服务。但是在VS中,下面的代码行显示为灰色。这意味着格雷码是无效的,对吗? (这两行是灰色的)

ControllerNTService service =new ControllerNTService(); Console.ReadLine();

如果代码有效,我想我可以碰到它们。

另一个问题,使用上面的代码,当我按F5进行调试时,它显示它无法调试它,我需要先安装服务。

我希望有人遇到类似的问题来指导我。 祝你有愉快的一天

1 个答案:

答案 0 :(得分:1)

您应该检查项目的活动Build配置。它需要设置为“DEBUG”。 (我认为按照你的描述设置为“RELEASE”)

您可以使用菜单构建更改活动的构建配置 - > ConfigurationManager中...->在Dialog中将Active Solution Configuratio设置为“DEBUG”。

如果要从命令行启动服务,还需要启动它。因此,您应该向ControllerNTService添加一个Start方法,该方法在实例

上调用受保护的OnStart方法
public class ControllerNTService{
   // additional service code

   internal void Start(string[] args) {
     base.OnStart(args);
   }

   internal void Stop() {
     base.OnStop();
   }
}

在main方法中,您应该在服务实例上调用Start。

ControllerNTService service =new ControllerNTService();
service.Start(args);
Console.ReadLine();
service.Stop();

除了启动它之外,最好还提供一种停止服务的方法(调用已获取的方法OnStop)。在Console.ReadLine之后调用此方法以停止服务。