我想在Windows XP机器上调试Visual Studio 2005中的Windows服务。我可以安装Windows服务并从管理控制台启动它。但是,进程在可用进程列表中显示为禁用,我无法将调试器附加到它。我能做些什么来启用可用进程列表中的进程?调试Windows服务
谢谢!
我想在Windows XP机器上调试Visual Studio 2005中的Windows服务。我可以安装Windows服务并从管理控制台启动它。但是,进程在可用进程列表中显示为禁用,我无法将调试器附加到它。我能做些什么来启用可用进程列表中的进程?调试Windows服务
谢谢!
您可能没有权限附加到进程。确保您已从管理帐户启动Visual Studio。
我有一个小窍门,允许轻松调试。它基本上把服务变成一个命令行应用程序,所以你可以调试它。下面是代码:
一下添加到Program.cs中(无效的主要()
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new PollingService() };
ServiceBase.Run(ServicesToRun);
#else
// Debug code: this allows the process to run as a non-service.
MyService service = new MyServiceService();
service.OnStart(null);
//Use this to make the service keep running
// Shut down the debugger to exit
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
//Use this to make it stop
//System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
//service.OnStop();
#endif
然后添加这在服务OnStart方法内:
#if (!DEBUG)
protected override void OnStart(string[] args)
#else
public new void OnStart(string[] args)
#endif
,这对调用OnStop方法
#if (!DEBUG)
protected override void OnStop()
#else
public new void OnStop()
#endif
有一对夫妇在这里有用的选项。
首先,我会建议为所有的Windows服务编写Main()例程,以支持将它们作为Windows服务或控制台应用程序运行。这样,您可以在控制台上运行,以便更轻松地进行调试。一个简化的main()例程看起来是这样的:
private static void Main(string[] args)
{
_service = new Service();
if (args.Length == 0 && !Debugger.IsAttached)
{
Run(new ServiceBase[] {_service});
}
else
{
Console.WriteLine("Starting Service...");
_service.OnStart(new string[0]);
Console.WriteLine("Service is running... Hit ENTER to break.");
Console.ReadLine();
_service.OnStop();
}
}
您可以更大胆,并支持不同的参数对于像帮助,控制台,服务,安装,卸载。
另一种选择是在代码中添加一个Debugger.Break()语句。然后,您可以像平常一样运行该服务,当它达到该点时,它将提示用户附加一个调试器。
这正是我所需要的。 – 2010-02-24 10:25:55
为了这个工作,OnStart和OnStop必须从'protected override'更改为'public new' – 2011-04-15 22:54:45
@Gabriel McAdams,如果您将Main类放入服务中,则不行。 – 2011-04-17 14:45:16
+1正要说这个。 – 2010-01-14 04:39:05