---
title: "在VS2005中调试Windows Service"
author: "winzenghua"
date: "2007-08-15T17:14:00Z"
tags: []
slug: "vs2005-windows-service"
draft: false
lastmod: "2007-08-15T17:14:00Z"
id: 952952
url: "https://java4gis.iteye.com/blog/952952"
---

1\. MSDN推荐的方法  
1.1、调试windows服务的初始化、启动  
另写一个程序控制服务的初始化和启动

注意：OnStart里写Log, OnStart里要在30秒返回. 不然启动就失败了! 所以OnStart里不要放太多代码! 可以用异步或线程.

1.2、调试windows服务的其他方面  
1 ) 安装您的服务 : intallutils xx.exe  
2\) 可从“服务控制管理器”、“服务器资源管理器”或代码启动服务  
3\) vs: 设置相关断点，启动调试，再在工具栏中选择 调试-&gt;附加到进程..., 选择您的服务, 确定。

2、trace方法  
2.1、添加调试方法  
private static void DebugRun(string\[] args)  
{  
/*  
初始化服务  
OnStart();  
Console.ReadLine();  
OnStop();  
\*/  
}

2.2、改写程序入口为如下：  
public static void Main(string\[] args)  
{  
#if DEBUG  
DebugRun(args);  
#else  
/*  
初始化服务  
\*/  
#endif  
}

2.3、加入2种调试代码  
EventLog.WriteEntry("...");  
System.Diagnostics.Debug.WriteLine("...");