Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法调试Windows服务_C#_Windows_Debugging_Windows Services - Fatal编程技术网

C# 无法调试Windows服务

C# 无法调试Windows服务,c#,windows,debugging,windows-services,C#,Windows,Debugging,Windows Services,为了找到如何调试Windows服务,我查阅了几篇文章。 我发现如果我将以下代码放入我的OnStart()函数中: Debugger.Launch(); 这样做,但在我通过CMD(NET start)启动windows服务后,它只是启动并正常运行,但调试器从未启动,即使VS是用加载的windows服务打开的 我觉得我遗漏了什么,是什么?您可以尝试在OnStart方法中包含这一点: while(!System.Diagnostics.Debugger.IsAttached) { Syste

为了找到如何调试Windows服务,我查阅了几篇文章。 我发现如果我将以下代码放入我的
OnStart()
函数中:

Debugger.Launch();
这样做,但在我通过CMD(NET start)启动windows服务后,它只是启动并正常运行,但调试器从未启动,即使VS是用加载的windows服务打开的


我觉得我遗漏了什么,是什么?

您可以尝试在
OnStart
方法中包含这一点:

while(!System.Diagnostics.Debugger.IsAttached)
{
    System.Threading.Thread.Sleep(100);
}
然后,从VisualStudio菜单中手动附加到进程:调试->附加到进程

此外,请注意,本主题的备注部分指出:

如果已附加调试器,则不会发生任何事情


我通过修改服务的主方法来实现这一点,它位于Program.cs中,默认情况下如下所示:

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new ServiceMain() };
ServiceBase.Run(ServicesToRun);
然后,您可以使用查找您的服务是否像服务或调试器一样启动:

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();
}

当然,您必须在服务中添加StartForDebugging方法,并执行与OnStart方法相同的操作,或者您可以直接调用OnStart方法,只是将其公开。

哪个过程?我的服务?是的,您的服务的进程。我的服务的进程是灰色的(我无法单击它)。因此,这意味着您已经有一个调试器连接到它。您必须在不调试的情况下运行服务。啊,如果我从NET start启动它,它将没有调试器,不是吗?也许您可以集成以帮助您调试windows服务。