技术开发 频道

如何创建一个标准的Windows服务

  【IT168 技术文档】在很多时候,我们需要一个定时器,当间隔某段时间或者在某一个时刻的时候,触发某个业务的处理,这个时候,我们就可能需要引入Windows服务来做这个事情,如某些数据的同步操作、某些工作任务的创建或者侦听某些端口的工作等等。

  做过Windows Forms开发的人,对开发Windows服务可能会熟悉一些,其实它本身应该算是一个Windows Forms程序。基本上整个Windows服务的程序分为几个部分:安装操作实现、程序启动、服务操作等。

 本例子创建一个Windows服务,服务可以在整点运行,也可以在某段间隔时间运行,通过配置指定相关的参数。
完整的服务代码请下载文件进行学习:http://files.cnblogs.com/wuhuacong/AutoSyncService.rar 

  1.安装操作类的实现
  首先需要继承System.Configuration.Install.Installer类,并且需要增加ServiceProcessInstaller、ServiceInstaller两个对象来处理,另外您需要重载BeforeUninstall 和 AfterInstall 来实现服务在安装前后的启动和停止操作。


 

Code
    [RunInstaller(
true)]
    
public class ListenInstaller : Installer
    {
        
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller;
        
private System.ServiceProcess.ServiceInstaller serviceInstaller;

        
/// <summary>
        
/// 必需的设计器变量。
        
/// </summary>
        private System.ComponentModel.IContainer components = null;  

        
public ListenInstaller()
        {
            InitializeComponent();
            
//重新覆盖设计时赋予的服务名称
            this.serviceInstaller.DisplayName = Constants.ServiceName;
            
this.serviceInstaller.ServiceName = Constants.ServiceName;
        }
      

        
public override void Install(System.Collections.IDictionary stateSaver)
        {
            
base.Install(stateSaver);
        }


        
private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            ServiceController service
= new ServiceController(Constants.ServiceName);

            
if (service.Status != ServiceControllerStatus.Running)
            {
                
try
                {
                    service.Start();
                }
                
catch (Exception ex)
                {
                    EventLog loger;
                    loger
= new EventLog();
                    loger.Log
= "Application";
                    loger.Source
= Constants.ServiceName;
                    loger.WriteEntry(ex.Message
+ "\n" + ex.StackTrace, EventLogEntryType.Error);
                }
            }
        }

        
private void serviceInstaller_BeforeUninstall(object sender, InstallEventArgs e)
        {
            ServiceController service
= new ServiceController(Constants.ServiceName);

            
if (service.Status != ServiceControllerStatus.Stopped)
            {
                
try
                {
                    service.Stop();
                }
                
catch (Exception ex)
                {
                    EventLog loger;
                    loger
= new EventLog();
                    loger.Log
= "Application";
                    loger.Source
= Constants.ServiceName;
                    loger.WriteEntry(ex.Message
+ "\n" + ex.StackTrace, EventLogEntryType.Error);
                }
            }
        }
         ...............
     }
0
相关文章