最近由于工作需要,写了一个windows服务程序,有许多经验,我会陆续写出来。
 请原谅我从安装谈起,因为我一直有一个误区:只要从System.ServiceProcess.ServiceBase继承一个类并编译好就可以用.net提供的命令行程序InstallUtil.exe安装了。经过尝试,发现如果仅仅做了这样的一个类是无法用InstallUtil.exe安装的,在安装时会输出下面的信息:
 D:\>installutil windowsservice2.exe
 Microsoft (R) .NET Framework Installation utility Version 1.1.4322.573
 Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
 Running a transacted installation.
Beginning the Install phase of the installation.
 See the contents of the log file for the d:\windowsservice2.exe assembly's progr
 ess.
 The file is located at d:\windowsservice2.InstallLog.
 Installing assembly 'd:\windowsservice2.exe'.
 Affected parameters are:
    assemblypath = d:\windowsservice2.exe
    logfile = d:\windowsservice2.InstallLog
 No public installers with the RunInstallerAttribute.Yes attribute could be found
  in the d:\windowsservice2.exe assembly.
The Install phase completed successfully, and the Commit phase is beginning.
 See the contents of the log file for the d:\windowsservice2.exe assembly's progr
 ess.
 The file is located at d:\windowsservice2.InstallLog.
 Committing assembly 'd:\windowsservice2.exe'.
 Affected parameters are:
    assemblypath = d:\windowsservice2.exe
    logfile = d:\windowsservice2.InstallLog
 No public installers with the RunInstallerAttribute.Yes attribute could be found
  in the d:\windowsservice2.exe assembly.
 Remove InstallState file because there are no installers.
The Commit phase completed successfully.
The transacted install has completed.
 这是因为installUtil.exe会用反射的方法去查找所有把RunInstallerAttribute设置为true的System.Configuration.Install.Installer类型,并执行上面的Install方法,当找不到的时候,安装就失败了。
 所以我们必须要写一个从Installer类继承的类来满足installUtil.exe的要求。
由于windows服务的特殊性,其调试和通常的程序调试有一定的差别,下面我分别介绍几种方法:
 1、微软推荐的方法
 1.1、调试windows服务的初始化、启动
 另写一个程序控制服务的初始化和启动
1.2、调试windows服务的其他方面
 就是附加到操作系统进程的方法
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("...");









