简体   繁体   English

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

[英]Debug WindowsService in Visual Studio using preprocessor directive #if

When I use VS2010 SP1, I write a windows service. 使用VS2010 SP1时,我编写了Windows服务。 Now I want to debug it without installing it. 现在,我想调试它而不安装它。 So I write code in Program.cs main method as below: 所以我在Program.cs主要方法中编写代码,如下所示:

#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

I expected to debug the windows service in VS 2010. But in VS, the code lines below shows gray. 我希望在VS 2010中调试Windows服务。但是在VS中,下面的代码行显示为灰色。 It means the gray codes are invalid, am I right? 这意味着格雷码无效,对吗? (the two lines are gray) (这两行是灰色的)

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

If the codes are valid, I think I can run into them. 如果代码有效,我想我可以碰到它们。

Another question, using code above, when I press F5 to debug it, it shows that it is not able to debug it, I need to install the service first. 另一个问题,使用上面的代码,当我按F5对其进行调试时,表明它无法调试,我需要首先安装该服务。

I hope someone encountered similar issue to guide me. 我希望有人遇到类似的问题来指导我。 Have a nice day 祝你今天愉快

You should check the active Build configuration of your project. 您应该检查项目的活动Build配置。 It needs to be set to "DEBUG". 需要将其设置为“ DEBUG”。 (I think it is set to "RELEASE" by what you describe) (我认为您所描述的设置为“ RELEASE”)

You can change the active Build configuration using Menu Build -> ConfigurationManager...-> In the Dialog set the Active Solution Configuratio to "DEBUG". 您可以使用菜单Build-> ConfigurationManager ...->更改活动的Build配置。在对话框中,将Active Solution Configuratio设置为“ DEBUG”。

If you want to start your service from command line you also need to start it. 如果要从命令行启动服务,则还需要启动它。 Therefore you should add a Start method to your ControllerNTService that calls the protected OnStart method on the instance 因此,您应该将Start方法添加到ControllerNTService,以在实例上调用受保护的OnStart方法

public class ControllerNTService{
   // additional service code

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

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

In your main method then you should call Start on the service instance. 在您的主要方法中,您应该在服务实例上调用Start。

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

In addition to starting it is also a good idea to provide a method to stop the service (which calls the procted method OnStop). 除了启动之外,最好提供一种停止服务的方法(该方法称为procted方法OnStop)。 This method is called after the Console.ReadLine to stop the service. 在Console.ReadLine之后调用此方法以停止服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM