我们一般在调试Windows Service时,可以通过Tools->Attach to process,然后选中进程进行调试,这样的比较麻烦,因为你不得先编译程序,安装服务,然后启动等等一系列的操作,严重浪费不必要的时间,有没有比较好的一点的方法呢?
第一步,要将Project 属性中的Application中的Out Type设为Console Applicaion。
第二步,要将主函数放在Service类里面,因为要访问Service的OnStart()和OnStop()方法, 而这两个方法的访问性都是Protected,无法改变的。
第三步,根据条件编译,在Debug下,运行Cosole程序就可以了,此时我说就要可设置断点时行调试了啊。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace NTService
{
partial class DBService : ServiceBase
{
private bool _active;
private Thread _serviceThread;
public static void Main(string[] args)
{
DBService _dbService = new DBService();
#if DEBUG
Console.WriteLine("Run as Console");
Thread thread = new Thread(new ParameterizedThreadStart(runService));
string cmd = string.Empty;
thread.Start(_dbService);
do
{
cmd = Console.ReadLine();
}
while (!cmd.Equals("quit", StringComparison.CurrentCultureIgnoreCase));
_dbService.OnStop();
#else
Console.WriteLine("Run as Service");
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { _dbService };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#endif
}
public static void runService(object obj)
{
DBService dbService = (DBService)obj;
dbService.OnStart(null);
}
public DBService()
{
InitializeComponent();
_active = false;
}
protected override void OnStart(string[] args)
{
Console.WriteLine("Servie start");
_serviceThread = new Thread(doDBService);
_serviceThread.Start();
}
protected override void OnStop()
{
_active = false;
_serviceThread.Join();
Console.WriteLine("Servie stop");
}
private void doDBService()
{
_active = true;
while (_active)
{
//TODO
System.Threading.Thread.Sleep(100);
}
}
}
}
大家有什么好的意见,请多提提...ths