C# 如何创建一个Windows服务(Windows Service)

Windows服务经常用来做一些定时任务处理,今天来说一下如何搭建一个Windows服务(基础篇,不喜勿喷)。

1、搭建一个Windows Servier,我是VS2017 .NET FrameWork4.5.2的框架。

在这里插入图片描述

2、进入Service设计界面,右击鼠标弹出菜单,选中“添加安装程序”。

在这里插入图片描述
3、点击“serviceInstaller1”,在“属性”窗体将ServiceName改为MyService,Description改为测试,DisplayName改为Windows服务自动测试,StartType保持为Automatic

在这里插入图片描述
4、点击“serviceProcessInstaller1”,在“属性”窗体将Account改为 LocalService

在这里插入图片描述
5、选择工具 --》选择工具拖项 --》 Timer。

在这里插入图片描述
6、选择工具箱,拖动到“Service.cs”设计界面.

在这里插入图片描述
7、点击时间控件,写入自己业务代码。

在这里插入图片描述

using System;
using System.ServiceProcess;
using System.Threading;

namespace MyService
{
    public partial class Service1 : ServiceBase
    {
        private Thread thdStart;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            thdStart = new Thread(new ThreadStart(timer1.Start));
            thdStart.Start();
        }

        protected override void OnStop()
        {
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.timer1.Stop();
            string filePath = @"F:\Demo\MyService\MyService\测试\test.log";
            string strCont = "打印时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            System.IO.File.AppendAllText(filePath, strCont);
            this.timer1.Start();
        }
    }
}

8、生成项目解决方案,打开项目目录到Debug目录下面,新建两个install.batuninstall.bat批处理文件(直接建.txt文件再改后缀即可)。
install.bat:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /i MyService.exe
uninstall.bat:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /u MyService.exe
在这里插入图片描述

9、如果运行出现“InstallUtil.InstallLog”日志中出现如下图,请看我第一篇

在这里插入图片描述
按照第一篇操作,我的结果在这里啦:

在这里插入图片描述

不会写代码的程序猿初次写博客,有问题请大家多多指教,谢谢。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值