在.Net中用C#創建Windows Service,其實很簡單,按照以下的步驟就可以做出一個簡單的Windows Service。
1.首先在創建工程的時候選擇Windows Service,這樣.Net會自動生成Windows Service的框架;
2.完成Windows Service的相應事件,主要是OnStart和OnStop這兩個事件,完成後大致代碼如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Threading;
namespace WinSDemo
{
public class WinSDemo : System.ServiceProcess.ServiceBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private bool blnStopThread;
private Thread thdMain;
public WinSDemo()
{
// This call is required by the Windows.Forms Component Designer.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
}
// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinSDemo() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// WinSDemo
//
this.CanPauseAndContinue = true;
this.ServiceName = "MyTest";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
thdMain=new Thread(new ThreadStart(WriteLog));
thdMain.Start();
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
blnStopThread=true;
thdMain.Join();
}
protected override void OnPause()
{
thdMain.Suspend();
}
protected override void OnContinue()
{
thdMain.Resume();
}
protected void WriteLog()
{
StreamWriter myWriter=null;
do
{
Process.Start("net","send localhost yourValue");
try
{
myWriter=new StreamWriter("c://MyLog.txt",true);
myWriter.WriteLine(DateTime.Now.ToString());
myWriter.Close();
}
catch{};
Thread.Sleep(5000);
}while(blnStopThread==false);
}
}
}
注:為了使自己能更好的識別自己寫的Windows Service,建議在InitializeComponent修改Service的名稱。
3.為了使自己寫的Service能加載到系統中去,光靠以上步驟是不夠;接下來,向當前的工程添加Service Installer,在其中設置Service安裝後的起始狀態,代碼如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace WinSDemo
{
/// <summary>
/// Summary description for WinSDemoIns.
/// </summary>
[RunInstaller(true)]
public class WinSDemoIns : System.Configuration.Install.Installer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public WinSDemoIns()
{
// This call is required by the Designer.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
// Service will run under system account
processInstaller.Account = ServiceAccount.LocalSystem;
// Service will have Start Type of Manual
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "MyTest";
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}
4.完成以上的步驟,代碼的部分就完成了,編譯成可執行文件,再用.Net的Service安裝工具就行了,即在Dos窗口中,鍵入“installutil yourService.exe”,這樣執行就可以了,相反,如果想卸載Service的話,加一個參數就可以了,即“installutil /u yourService.exe”。注意有可能.Net的路徑在環境變量中不存在,可能直接執行是不能成功的,希望先找到“installutil.exe”存在的目錄,大致在“/WINDOWS/Microsoft.NET/Framework/v1.1.4322”目錄下。
至於以後Service的部署,由於.Net寫的程序,運行環境必須要安裝.Net Framework,所以在其他機器安裝自己寫的Service時候,一定要先安裝.Net運行環境。