Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:23:29 C#教程:创建Windows服务
C#教程:创建Windows服务
创建Windows服务首先介绍.NET框架下与Windows服务相关的命名空间及其中的类库。.NET框架大大地简化了Windows服务程序的创建和控制过程,这要归功于其命名空间中的功能强大的类库。与Windows服务程序相关的命名空间主要有以下两个:System.ServiceProcess和System. Diagnostics。如图1所示,要创建一个最基本的Windows服务程序,只需要运用.Net框架下的System.ServiceProcess命名空间以及其中的4个类:ServiceBase、ServiceInstaller、ServiceProcessInstaller以及ServiceController。其中,ServiceBase类定义了一些可被其子类重载的方法,通过这些可重载方法,服务控制管理器就可以控制Windows服务程序。可重载方法主要包括:OnStart、OnStop、OnPause和OnContinue等方法。图1 System.ServiceProcess命名空间下的基类另外,ServiceBase类的子类还可以重载OnCustomCommand方法来完成一些特定的操作。通过重载以上的一些方法,可以创建一个基本的Windows服务程序框架,重载方法的实现代码如下:protected override void OnStart(string[] args){}protected override void OnStop(){}protected override void OnPause(){}protected override void OnContinue(){}要使一个Windows服务程序能够正常运行,必须像创建一般应用程序那样为它创建一个程序的入口点。在.Visual Studio 2005开发环境中创建Windows服务启动程序时,必须在主程序文件Program.cs中添加服务启动代码。Windows服务的启动代码如下:static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(False);// Application.Run(new Form1());System.ServiceProcess.ServiceBase.Run(new FileService());}上述代码启动一个服务名为FileService的Windows服务,如果要启动多个Windows服务,可以通过数组来实现,其关键代码如下:static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(False);// Application.Run(new Form1());//System.ServiceProcess.ServiceBase.Run(new FileService());System.ServiceProcess.ServiceBase[] MyServices;MyServices = new System.ServiceProcess.ServiceBase[] { new FileService(), new CareEye.() };System.ServiceProcess.ServiceBase.Run(MyServices);}下面创建一个Windows服务,当服务开启时,向一个文件写入启动内容;当服务停止时,向文件写入结束内容。创建Windows服务的步骤如下所示。(1)运行Visual Studio 2005开发环境,建立一个“Windows应用程序”项目,命名为“FileServer.cs”,如图2所示。在“FileServer.cs”类文件中写入两个方法:Start方法和Stop方法。Start方法在服务启动时自动调用。Stop方法在服务停止时自动调用。Start方法和Stop方法关键代码如下:图2 创建Windows应用程序public void Start(){FileStream fs = new FileStream(@"d:FileServer.txt", FileMode.OpenOrCreate, FileAccess.Write);StreamWriter m_streamWriter = new StreamWriter(fs);m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);m_streamWriter.WriteLine("FileServer: Service Started" + " " + "操作时间" + DateTime.Now.ToString() + "n");m_streamWriter.WriteLine("服务已起动" + " " + "操作时间" + DateTime.Now.ToString() + "n");m_streamWriter.Flush();m_streamWriter.Close();fs.Close();}public void Stop(){FileStream fs = new FileStream(@"d:FileServer.txt", FileMode.OpenOrCreate, FileAccess.Write);StreamWriter m_streamWriter = new StreamWriter(fs);m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);m_streamWriter.WriteLine(" FileServer: Service Stopped " + " " + "结束时间"+DateTime.Now.ToString() + "n");m_streamWriter.WriteLine("服务已停止" + " " + "操作时间" + DateTime.Now.ToString() + "n");m_streamWriter.Flush();m_streamWriter.Close();fs.Close();}(2)项目创建完成后,新建一个Windows服务。右键单击“项目名称”,从弹出的快捷菜单中选择“添加”/“添加新项”选项,弹出“添加新项”对话框,在该对话框中选择“Windows 服务”选项,并将其命名为“FileService.cs”,如图3所示。
赞