C# 创建Windows Service

当我们需要一个程序长期运行,但是不需要界面显示时可以考虑使用Windows Service来实现。这篇博客将简单介绍一下如何创建一个Windows Service,安装/卸载Windows Service。

新建Windows Service项目:

删除自动生成的Service1.cs文件,新建WindowsService类,继承ServiceBase。

    class WindowsService : ServiceBase
    {
        public WindowsService()
        {
            this.ServiceName = "Test Windows Service";
            this.EventLog.Log = "Application";

            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;
        }

        #region
        // 可以把需求实现代码放置在重写方法内
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            base.OnStop();
        }

        protected override void OnPause()
        {
            base.OnPause();
        }

        protected override void OnContinue()
        {
            base.OnContinue();
        }

        protected override void OnShutdown()
        {
            base.OnShutdown();
        }

        protected override void OnCustomCommand(int command)
        {
            base.OnCustomCommand(command);
        }

        protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
        {
            return base.OnPowerEvent(powerStatus);
        }

        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            base.OnSessionChange(changeDescription);
        }
        #endregion
    }

新建WindowsServiceInstaller类,添加System.Configuration.Install引用,

    [RunInstaller(true)]
    class WindowsServiceInstaller : Installer
    {
        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
            serviceProcessInstaller.Username = null;
            serviceProcessInstaller.Password = null;

            serviceInstaller.DisplayName = "CSharp Windows Service";
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            serviceInstaller.ServiceName = "Windows Service";

            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }

编译项目,此时编译完的CSWindowsService.exe运行后提示:

我们需要通过installutil.exe来部署Windows Service。

以管理员身份运行Developer Command Prompt。部署命令:installutil /i 文件路径

例如:installutil /i D:\CSWindowsService.exe

卸载命令 installutil /u 文件路径。

到这里,一个简单的Windows Serive就讲完了。

关于Windows Service更多的内容,请参考MSDN文档。

感谢您的阅读,代码点击这里下载。

posted @ 2015-08-18 21:21  Yang-Fei  阅读(972)  评论(0编辑  收藏  举报