惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V2EX - 技术
V2EX - 技术
T
Troy Hunt's Blog
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Secure Thoughts
Hacker News - Newest:
Hacker News - Newest: "LLM"
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
博客园 - Franky
有赞技术团队
有赞技术团队
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
NISL@THU
NISL@THU
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Recent Commits to openclaw:main
Recent Commits to openclaw:main
K
Kaspersky official blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
W
WeLiveSecurity
SecWiki News
SecWiki News
Google DeepMind News
Google DeepMind News
O
OpenAI News
V
V2EX
AI
AI
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 三生石上(FineUI控件)
G
GRAHAM CLULEY
月光博客
月光博客
T
Threatpost
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Vulnerabilities – Threatpost
Last Week in AI
Last Week in AI
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cloudbric
Cloudbric
酷 壳 – CoolShell
酷 壳 – CoolShell
The Hacker News
The Hacker News
N
News | PayPal Newsroom
Know Your Adversary
Know Your Adversary

博客园 - aierong

CommunityToolkit.Mvvm系列文章导航 CommunityToolkit.Mvvm8.1 IOC依赖注入控制反转(5) CommunityToolkit.Mvvm8.1 消息通知(4) CommunityToolkit.Mvvm8.1 viewmodel源生成器写法(3) wpf RelativeSource绑定 CommunityToolkit.Mvvm8.1 viewmodel使用-旧式写法(2) CommunityToolkit.Mvvm8.1 MVVM工具包安装引用指南(1) Jquery利用ajax调用asp.net webservice的各种数据类型(总结篇) .NET中对串口(COM)读写操作方式汇总 Sql Server2008 Transact-SQL 新兵器学习总结之-用户定义表类型和日期,时间数据类型 Air版免费视频成人聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))<视频聊天,会议开发实例7> Flex(flash)检测摄像头的3种状态(是否被占用,没安装摄像头,正常) - aierong - 博客园 Flex Air开发SQLite小结,SQLite开发工具及SQLite与Sql Server的语法差异汇总 开源Flex Air版免费激情美女视频聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))<视频聊天,会议开发实例6> 免费网络远程视频会议系统,免费美女多人视频聊天(附源码下载)(Flex和Fms3开发)<视频聊天,会议开发实例5> Flex组件的项目渲染器(ItemRenderer)使用总结 推荐几个Adobe Flex Builder 3的插件(代码格式化和fms服务器通讯文件(main.asc)编写) Flex组件开发总结-20090209 免费美女视频聊天,多人视频会议功能加强版本(Fms3和Flex开发(附源码))<视频聊天,会议开发实例4>
创建Windows服务(Windows Services)N种方式总结
aierong · 2012-05-28 · via 博客园 - aierong

最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。
目前我知道的创建创建Windows服务有3种方式:
a.利用.net框架类ServiceBase
b.利用组件Topshelf
c.利用小工具instsrv和srvany

下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志:

a.利用.net框架类ServiceBase

本方式特点:简单,兼容性好

通过继承.net框架类ServiceBase实现

第1步: 新建一个Windows服务

    public partial class Service1 : ServiceBase
    {
        readonly Timer _timer;

        private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @"\" + "test.txt";

        public Service1 ( )
        {
            InitializeComponent ( );

            _timer = new Timer ( 5000 )
            {
                AutoReset = true ,
                Enabled = true
            };

            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }

        protected override void OnStart ( string [ ] args )
        {
            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
        }

        protected override void OnStop ( )
        {
            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
        }

        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }

    }

第2步: 添加Installer

    [RunInstaller ( true )]
    public partial class Installer1 : System.Configuration.Install.Installer
    {
        private ServiceInstaller serviceInstaller;
        private ServiceProcessInstaller processInstaller;

        public Installer1 ( )
        {
            InitializeComponent ( );

            processInstaller = new ServiceProcessInstaller ( );
            serviceInstaller = new ServiceInstaller ( );

            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            serviceInstaller.ServiceName = "my_WindowsService";
            serviceInstaller.Description = "WindowsService_Description";
            serviceInstaller.DisplayName = "WindowsService_DisplayName";

            Installers.Add ( serviceInstaller );
            Installers.Add ( processInstaller );
        }  
    }

第3步:安装,卸载
Cmd命令
installutil      WindowsService_test.exe  (安装Windows服务)
installutil /u   WindowsService_test.exe  (卸载Windows服务)

代码下载:https://files.cnblogs.com/aierong/WindowsService_test.rar

b.利用组件Topshelf

本方式特点:代码简单,开源组件,Windows服务可运行多个实例

Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com

第1步:引用程序集TopShelf.dll和log4net.dll

第2步:创建一个服务类MyClass,里面包含两个方法Start和Stop,还包含一个定时器Timer,每隔5秒往文本文件中写入字符

    public class MyClass
    {
        readonly Timer _timer;

        private static readonly string FileName = Directory.GetCurrentDirectory ( ) + @"\" + "test.txt";

        public MyClass ( )
        {
            _timer = new Timer ( 5000 )
            {
                AutoReset = true ,
                Enabled = true
            };

            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }

        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }

        public void Start ( )
        {
            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
        }

        public void Stop ( )
        {
            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
        }

    }

第3步:使用Topshelf宿主我们的服务,主要是Topshelf如何设置我们的服务的配置和启动和停止的时候的方法调用

    class Program
    {
        static void Main ( string [ ] args )
        {
            HostFactory.Run ( x =>
            {
                x.Service<MyClass> ( ( s ) =>
                {
                    s.SetServiceName ( "ser" );
                    s.ConstructUsing ( name => new MyClass ( ) );
                    s.WhenStarted ( ( t ) => t.Start ( ) );
                    s.WhenStopped ( ( t ) => t.Stop ( ) );
                } );

                x.RunAsLocalSystem ( );

                //服务的描述
                x.SetDescription ( "Topshelf_Description" );
                //服务的显示名称
                x.SetDisplayName ( "Topshelf_DisplayName" );
                //服务名称
                x.SetServiceName ( "Topshelf_ServiceName" );

            } );
        }
    }

第4步: cmd命令

ConsoleApp_Topshelf.exe  install    (安装Windows服务)

ConsoleApp_Topshelf.exe  uninstall  (卸载Windows服务)

代码下载:https://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar

c.利用小工具instsrv和srvany

本方式特点:代码超级简单,WindowsForm程序即可,并支持程序交互(本人最喜欢的特点),好像不支持win7,支持xp win2003

首先介绍2个小工具:

instsrv.exe:用以安装和卸载可执行的服务

srvany.exe:用于将任何EXE程序作为Windows服务运行

这2个工具都是是Microsoft Windows Resource Kits工具集的实用的小工具 

你可以通过下载并安装Microsoft Windows Resource Kits获得 http://www.microsoft.com/en-us/download/details.aspx?id=17657

第1步: 新建WindowsForm程序

   public partial class Form1 : Form
    {
        Timer _timer;

        private static readonly string FileName = Application.StartupPath + @"\" + "test.txt";

        public Form1 ( )
        {
            InitializeComponent ( );
        }

        private void Form1_Load ( object sender , EventArgs e )
        {
            _timer = new Timer ( )
            {
                Enabled = true ,
                Interval = 5000
            };

            _timer.Tick += delegate ( object _sender , EventArgs _e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }

        void _timer_Tick ( object sender , EventArgs e )
        {
            throw new NotImplementedException ( );
        }

        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }

        private void button1_Click ( object sender , EventArgs e )
        {
            MessageBox.Show ( "Hello" );
        }

    }

第2步:安装,卸载

服务的安装步骤分5小步:

(1)打开CMD,输入以下内容,其中WindowsForms_WindowsService为你要创建的服务名称

格式:目录绝对路径\instsrv  WindowsForms_WindowsService  目录绝对路径\srvany.exe

例如:

D:\TempWork\win\Debug\instsrv.exe  WindowsForms_WindowsService  D:\TempWork\win\Debug\srvany.exe

(2)regedit打开注册表编辑器,找到以下目录

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WindowsForms_WindowsService

(3)鼠标右键单击WindowsForms_WindowsService,创建一个"项",名称为"Parameters"

(4)鼠标左键单击"Parameters",在右边点击鼠标右键,创建一个"字符串值"(REG_SZ),名称为"Application",数值数据里填写目录下可执行文件的绝对路径+文件名

例如:

D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe

(5)打开services.msc服务控制面板,找到WindowsForms_WindowsService服务,鼠标右键-属性-登陆,勾选"允许服务与桌面交互"

启动服务,可以看到程序界面

卸载服务

D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService REMOVE

代码下载:https://files.cnblogs.com/aierong/WindowsFormsApplication_Exe.rar