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服务程序?
相关推荐
一阵没来由的风1 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
cpsvps2 小时前
美国服务器环境下Windows容器工作负载基于指标的自动扩缩
windows
网硕互联的小客服5 小时前
Apache 如何支持SHTML(SSI)的配置方法
运维·服务器·网络·windows·php
etcix5 小时前
implement copy file content to clipboard on Windows
windows·stm32·单片机
许泽宇的技术分享6 小时前
Windows MCP.Net:基于.NET的Windows桌面自动化MCP服务器深度解析
windows·自动化·.net
非凡ghost7 小时前
AMS PhotoMaster:全方位提升你的照片编辑体验
windows·学习·信息可视化·软件需求
一枚小小程序员哈7 小时前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
mortimer8 小时前
一次与“顽固”外部程序的艰难交锋:subprocess 调用exe踩坑实录
windows·python·ai编程
Eternity_GQM9 小时前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
gameatp10 小时前
从 Windows 到 Linux 服务器的全自动部署教程(免密登录 + 压缩 + 上传 + 启动)
linux·服务器·windows