C# 编写Windows服务程序

1.什么是windows服务?

Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。

2.如何创建windows服务项目?
2.1 项目创建

如下图:

2.2 代码实例

代码如下:

cs 复制代码
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 WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
         Timer timer1 = new Timer();//定时器

        //开始
        protected override void OnStart(string[] args)
        {
            timer1.Interval = 1000;//设置计时器事件间隔执行时间
            timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
        }

        //结束
        protected override void OnStop()
        {
            timer1.Enabled = false; 
        }
        //定时任务
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Task.Run(() => { File.AppendAllText(@"D: hello.txt", DateTime.Now.ToString("yyyy年M月dd日 hh:mm:ss:fff") + Environment.NewLine); });
        }


    }
}
3.如何在本地测试windows服务项目?

3.1 首先打开设计界面,右击设计界面,如下图。

3.2 然后根据下图修改属性。

4.如何在windows系统上发布Windows项目?
5.使用winfrm控制Windows服务程序?
相关推荐
Vex2une6 小时前
电脑风扇吵、温度高怎么办?清灰、硅脂更换与风扇曲线调节指南
windows·清灰·电脑散热·风扇噪音大·硅脂更换·风扇曲线·cpu温度高
feasibility.10 小时前
电脑一天重启3次、WiFi还消失:蓝屏0x9F背后,是MT7921网卡撞上Windows电源管理
服务器·网络·windows·wifi·电脑·网卡·驱动
StarsGreen15 小时前
Android系统相关命令介绍
android·windows
张人玉2 天前
C#如何使用FreeSql连接数据库
数据库·c#·freesql
争不过朝夕,又念着往昔2 天前
C++20-概念与约束
windows·c++20
郝学胜-神的一滴2 天前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
吴可可1232 天前
C#打断多段线实现方法
c#
Kari112 天前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
解道Jdon3 天前
Rust重写OpenCode Rune:性能提升最高100倍
ide·windows·git·svn·eclipse·github·visual studio
Frag0ut3 天前
开源下载管理器MDM下载获取与实操指南:IDM的上位替代
windows·macos·mdm·下载管理器·断点续传·开源下载工具·idm替代