【问题标题】:debugging window service调试窗口服务
【发布时间】:2011-10-23 03:49:49
【问题描述】:
我想调试窗口服务。我应该在 main() 中写什么来启用窗口服务中的调试。我正在使用 C# 开发窗口服务。
#if(DEBUG)
System.Diagnostics.Debugger.Break();
this.OnStart(null);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase.Run(this);
#endif
我写了上面的代码段但是在线(这个
【问题讨论】:
标签:
c#
debugging
windows-services
【解决方案1】:
我会这样做:
在您服务的 OnStart 方法中,在顶部添加对 Debugger.Break() 的调用:
protected override void OnStart(string[] args)
{
#if DEBUG
Debugger.Break();
#endif
// ... the actual code
}
【解决方案2】:
试试这个:
#if DEBUG
while (!System.Diagnostics.Debugger.IsAttached)
{
Thread.Sleep(1000);
}
System.Diagnostics.Debugger.Break();
#endif
它一直等到您附加调试器,然后中断。
【解决方案3】:
我个人使用这种方法调试一个Windows服务:
static void Main() {
if (!Environment.UserInteractive) {
// We are not in debug mode, startup as service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyServer() };
ServiceBase.Run(ServicesToRun);
} else {
// We are in debug mode, startup as application
MyServer service = new MyServer();
service.StartService();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
}
并在您的MyServer 类中创建一个将使用OnStart 事件的新方法:
public void StartService() {
this.OnStart(new string[0]);
}