windows服务开发

学然后知不足 教然后知困。

没做过windows service开发时,感觉很难,无从下手。再网看了些例子,加上自己的理解,写下开发步骤。

开发步骤

  1. 新建windows service
    1236909-20180316183816060-772451320.png

  2. 添加服务,发表后将再自己的电脑的 服务管理 查看到
    1236909-20180316183825978-1915696004.png

    partial class MyService : ServiceBase
    {
        Timer timer1;

        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.

            using (StreamWriter sw = File.AppendText(@"D:\\log2.txt"))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Start.");
            }

            timer1 = new Timer();
            timer1.Interval = 2000;
            timer1.Elapsed += (sender, e) =>
            {
                using (StreamWriter sw = File.AppendText(@"D:\\log2.txt"))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Countue...");
                }
            };
            timer1.Start();
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            using (StreamWriter sw = File.AppendText(@"D:\\log2.txt"))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Stop.");
            }
        }
    }
  1. 添加服务安装程序(这是vs给提供的方便操作),可以发表多个服务。
    1236909-20180316183837365-1598075934.png

右击,点击Add Installer,自动生成类ProjectInstaller。大家可以看下vs自动生成的类ProjectInstaller.Designer.cs文件

private void InitializeComponent()
        {
            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            //设置服务安装信息
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            //要安装的服务(保证与你的服务名一致,可添加多个)
            this.serviceInstaller1.ServiceName = "MyService";
            //服务加入
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller1,
            this.serviceInstaller1});

        }

注意将服务安装设置为:手动安装

  1. 服务安装卸载脚本
    Install.bat 文件:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "%~dp0%WindowsServiceTest.exe"
pause

Uninstall.bat文件:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u "%~dp0%WindowsServiceTest.exe"
pause

转载于:https://www.cnblogs.com/LoveTomato/p/8584026.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值