Paw*_*anS 81 c# windows-services visual-studio-2010 visual-studio
是否可以在Visual Studio中调试Windows服务?
我用的代码就像
System.Diagnostics.Debugger.Break();
Run Code Online (Sandbox Code Playgroud)
但它给出了一些代码错误,如:
我收到两个事件错误:eventID 4096 VsJITDebugger和"服务没有及时响应启动或控制请求."
Chi*_*rag 117
在服务OnStart
方法中使用以下代码:
System.Diagnostics.Debugger.Launch();
Run Code Online (Sandbox Code Playgroud)
从弹出消息中选择Visual Studio选项.
注意:要仅在调试模式下使用它,#if DEBUG
可以使用编译器指令,如下所示.这将防止生产服务器上的发布模式中的意外或调试.
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
Run Code Online (Sandbox Code Playgroud)
Paw*_*anS 60
你也可以试试这个.
(经过大量的谷歌搜索后,我在"如何在Visual Studio中调试Windows服务"中找到了这个.)
ang*_*son 21
您应该将所有将从服务项目中执行操作的代码分离到单独的项目中,然后创建一个可以正常运行和调试的测试应用程序.
服务项目只是实现服务部分所需的shell.
Pau*_*erø 14
要么就像Lasse V. Karlsen所建议的那样,要么在服务中设置一个等待调试器附加的循环.最简单的是
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
... continue with code
Run Code Online (Sandbox Code Playgroud)
这样你可以启动服务,在Visual Studio中你选择"附加到进程......"并附加到你的服务,然后恢复正常的服务.
鉴于ServiceBase.OnStart
具有protected
可见性,我沿着反射路线进行调试.
private static void Main(string[] args)
{
var serviceBases = new ServiceBase[] {new Service() /* ... */ };
#if DEBUG
if (Environment.UserInteractive)
{
const BindingFlags bindingFlags =
BindingFlags.Instance | BindingFlags.NonPublic;
foreach (var serviceBase in serviceBases)
{
var serviceType = serviceBase.GetType();
var methodInfo = serviceType.GetMethod("OnStart", bindingFlags);
new Thread(service => methodInfo.Invoke(service, new object[] {args})).Start(serviceBase);
}
return;
}
#endif
ServiceBase.Run(serviceBases);
}
Run Code Online (Sandbox Code Playgroud)
请注意,Thread
默认情况下是前台线程.return
从荷兰国际集团Main
,而人造服务线程运行不会终止进程.