当前位置:首页 > Windows程序 > 正文

初识Windows服务

2021-03-29 Windows程序

标签:

1.新建Windows服务

 

 

2.切换到代码视图,拷入如下代码

该服务以10S的间隔创建 d:/1.txt 文件

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers; namespace WindowsServiceTest { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { //服务开启执行代码 StartDoSomething(); } protected override void OnStop() { //服务结束执行代码 } protected override void OnPause() { //服务暂停执行代码 base.OnPause(); } protected override void OnContinue() { //服务恢复执行代码 base.OnContinue(); } protected override void OnShutdown() { //系统即将关闭执行代码 base.OnShutdown(); } private void StartDoSomething() { System.Timers.Timer timer = new System.Timers.Timer(10000); //间隔10秒 timer.AutoReset = true; timer.Enabled = false; //执行一次 timer.Elapsed += new ElapsedEventHandler(WriteSomething); timer.Start(); } private void WriteSomething(object source, System.Timers.ElapsedEventArgs e) { FileStream fs = null; try { fs = new FileStream("d:/1.txt", FileMode.OpenOrCreate); string strText = @"以10秒的间隔重复创建该文件,若已有同名文件,则保持不变"; //获得字节数组 byte[] data = new UTF8Encoding().GetBytes(strText); //开始写入 fs.Write(data, 0, data.Length); //清空缓冲区、关闭流 fs.Flush(); fs.Close(); fs.Dispose(); } catch { } finally { if (fs != null) { fs.Close(); fs.Dispose(); } } } } }

  

3.添加安装程序并设置控件属性

1.在设计页面右键,选择添加安装程序

 

2.将左上角第一个控件的Account属性设置为LocalService

3.可以自行修改第二个控件的ServiceName(服务名称,不可和系统已有的冲突),StartType设置为Automatic

4.编译项目

1.生成解决方案(Ctrl+Shift+B),编译完成后会生成对应的xxx.exe

2.找到系统里面InstallUtil的安装目录 例如 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe  实在找不到就用Everything吧

3.Win+R CMD  cd 跳转到InstallUtil的安装路径,,运行如下命令  InstallUtil.exe+空格+4.1生成的exe的目录

    cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

InstallUtil.exe E:\GitVSTest\WindowsServiceTest\WindowsServiceTest\bin\Debug\WindowsServiceTest.exe

5.启动服务

在计算机-管理-服务和应用程序-服务 里面找到刚才编译的服务,右键启动即可

 

6.修改服务

1.在服务里面,停止对应服务

 

2.修改源代码并再次生成解决方案(Ctrl+Shift+B)

3.再次启动服务

7.卸载服务

卸载服务运行的命名和4.3 类似

依然是在InstallUtil 目录下,不过是运行 InstallUtil.exe /u 生成的exe的目录

例如:C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe /u E:\GitVSTest\WindowsServiceT2\WindowsServiceT2\bin\Debug\WindowsServiceT2.exe

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69834.html