C#中如何建立Windows服務

来源:互联网 发布:java中什么是构造函数 编辑:程序博客网 时间:2024/05/10 02:50

在建立項目時﹐選擇Windows服務后就產生一個繼承自System.ServiceProcess.ServiceBase的類﹐主要在OnStart和OnStop中添加執行和釋放的方法,注意CanPauseAndContinue是可以設置是否允許中止服務的. 最關鍵的是安裝服務﹐直接用InstallUtil是不行的﹐還要在項目中添加一個Installer的繼承類。方法如下﹕

windows服务安装类代码

using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;

namespace WindowsService1
{
 /// <summary>
 /// myInstall 的摘要说明。
 /// </summary>
 ///
 [RunInstaller(true)]
 public class myInstall : Installer
 {

  private ServiceInstaller serviceInstaller;
  private ServiceProcessInstaller processInstaller;
  public myInstall()
  {
   processInstaller = new ServiceProcessInstaller();
   serviceInstaller = new ServiceInstaller();

   processInstaller.Account = ServiceAccount.LocalSystem;
   serviceInstaller.StartType = ServiceStartMode.Automatic;
   serviceInstaller.ServiceName = "WindowsService1"; //WindowsService1是你的服務類名

   Installers.Add(serviceInstaller);
   Installers.Add(processInstaller);
  }
 }
}

 編譯完成后﹐再運行InstallUtil.exe 服務名.exe. (注﹕InstallUtil.exe要在.net的命令工具中運行﹐否則要用完整的路徑名稱)
原创粉丝点击