方法2:附加进程
附加进程的方法可以像调试正常的widows程序一样,设置断点进行单步调试。但是必须在安装启动服务后,才可以进行附加此服务进程,可在附加的同时OnStart 函数已经执行完毕,所以对Onstart 无法调试(正常服务的启动时间为30秒左右,当服务启动时间超过30秒会报错)。需要通过设置启动服务延时来加载调试。设置有些繁琐;
方法3:修改Main函数,在用户交互模式下调试。调试时更改Project的输出类型为Console Application,就可以直接调试了。
if (Environment.UserInteractive)
{
Service1 s = new Service1();
string[] args = { "a", "b" };
s.start(args);
Console.WriteLine("the service is started");
Console.ReadLine();
s.stop();
Console.WriteLine("the service is stopped");
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
在应用非托管dll时,有时会提示找不到dll文件,可以依次尝试一下过程看会否有帮助:
1.复制dll文件到项目bin文件下;
2.复制dll文件到system32路径下;
3.在[DllImport]是加上dll文件路径;
另外,在开发window services程序时,使用的Timer控件需注意。如果使用System.Windows.Form.Timer控件,可能会不能正常运行,应使用System.Timers.Timer控件;
安装服务后,在删除服务时,可以直接使用SC.exe命令删除服务