当前位置:编程学习 > C#/ASP.NET >>

C#创建Windows服务

1.创建C#工程

  创建一个EXE工程,可以是WinForm或者命令行格式的。添加对System.ServiceProcess.dll和System.Configuration.Install.dll的引用。

 

2. 创建服务类

  新增一个类,该类型继承System.ServiceProcess.ServiceBase类型,在构造函数中设置ServiceName 属性来指明该服务的名称。然后重载它的OnStart方法来响应启动服务的事件,重载OnStop方法来响应停止服务的事件,重载OnPause方法来响 应暂停服务的事件,重载OnContinue方法来响应恢复提供服务的事件。 

  在重载这些方法时必须要立即返回,其中不能出现长时间的操作,若处理时间过长则Windows服务管理器会觉得该Windows服务停止响应而报错。为此 我们可以使用一个线程来进行实际的工作,而OnStart方法创建线程,OnStop方法关闭线程,OnPause方法挂起线程,而OnContinue 方法来恢复运行线程。

 

3.启动服务 

  在main函数中调用“System.ServiceProcess.ServiceBase.Run( 自定义服务类的实例 )”来运行服务。比如“System.ServiceProcess.ServiceBase.Run( new MyService() )”,这里的MyService就是继承自ServiceBase。

  注:以上步骤可以通过在VS2005中新建“Windows服务”项目,代码均由开发环境自动生成
-------------------------------------------------------------------------------------------------------------
 

 4、创建服务的安装类
 

  新增一个类,该类型继承自System.Configuration.Install.Installer类型,该类型用于配合微软.NET框 架自带的安装命令行工具InstallUtil.exe的。我们为该类型附加 System.ComponentModel.RunInstallerAttribute特性,

[RunInstaller(true)]
    public partial class ServiceInstaller :Installer
    {
        
        public ServiceInstaller()
        {
            InitializeComponent();
        }
    }

  并在它的构造函数中使用 System.ServiceProcess.ServiceInstaller对象和 System.ServiceProcess.ServiceProcessInstaller对象向系统提供该服务的安装信息。

\代码
 partial class ServiceInstaller
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        ///
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,