简体   繁体   English

无法调试Windows服务

[英]Unable to debug Windows Service

I was looking into several posts in order to find how to debug a Windows Service. 我正在调查几篇文章,以找到如何调试Windows服务。 I've found that if I put the following code in my OnStart() function: 我发现,如果将以下代码放入OnStart()函数中:

Debugger.Launch();

would do the trick, but after I start my windows service via the CMD (NET START), it just starts and runs properly but the debugger never launches, even though the VS is opened with the loaded windows service. 可以解决问题,但是当我通过CMD(NET START)启动Windows服务后,它就可以正常启动并运行,但是即使通过加载的Windows服务打开了VS,调试器也无法启动。

I feel like I'm missing something, what is it? 我觉得我想念什么,那是什么?

You may try to include this in the OnStart method: 您可以尝试将其包含在OnStart方法中:

while(!System.Diagnostics.Debugger.IsAttached)
{
    System.Threading.Thread.Sleep(100);
}

Then, manually attach to the process from the Visual Studio menu: Debug - > Attach to Process . 然后,从Visual Studio菜单手动附加到流程: 调试->附加到流程

Also, please note that in the Remarks section of the Debugger.Launch Method topic is stated that: 另外,请注意,在Debugger.Launch方法主题的“ 备注”部分中指出:

If a debugger is already attached, nothing happens. 如果已经连接了调试器,则不会发生任何事情。

I am doing that by modifing service's Main method, it's in the Program.cs and by default it looks like this : 我通过修改服务的Main方法来做到这一点,它在Program.cs中,默认情况下看起来像这样:

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new ServiceMain() };
ServiceBase.Run(ServicesToRun);

you can then use Environment.UserInteractive to find out is your service started like a service or trough debugger : 然后,您可以使用Environment.UserInteractive来确定您的服务是像服务或低谷调试器那样启动的:

if (!Environment.UserInteractive)
{
  ServiceBase[] ServicesToRun;
  ServicesToRun = new ServiceBase[] { new ServiceMain() };
  ServiceBase.Run(ServicesToRun);
}
else
{
  ServiceMain sm = new ServiceMain();
  Console.Write("Service debug run");
  sm.StartForDebugging();
}

Of course you will have to add StartForDebugging method in your service and do practically the same like you do in OnStart method, or you could call OnStart method directly just make it public. 当然,您将必须在服务中添加StartForDebugging方法,并且实际上与在OnStart方法中所做的一样,或者可以直接调用OnStart方法以使其公开。

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

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