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服务程序?
相关推荐
一只积极向上的小咸鱼2 小时前
Codex 在 VS Code + ModelArts 场景下的登录与配置总结
linux·运维·windows
飞鸿踏雪(蓝屏选手)6 小时前
137 ≤ Chrome 主密钥获取研究
c++·chrome·windows·网络安全·逆向分析
阿虎儿9 小时前
[实战记录] Windows 11 远程桌面已开启,但 3389 端口无监听?终极排查与修复
windows
yong999010 小时前
C# 实时查看硬件使用率(CPU 内存 硬盘 网络)
开发语言·网络·c#
神仙别闹12 小时前
基于 C# OpenPGP 的文件管理系统
开发语言·c#
Andy13 小时前
C++ list容器基本逻辑结构详解
c++·windows·list
海盗123414 小时前
C#在Distinct()中使用IEqualityComparer<T>
开发语言·c#
扬帆破浪16 小时前
免费开源AI软件.桌面单机版,可移动的AI知识库,察元 AI桌面版:免费开源的AI软件首启动 FirstRunSetup向导背后做了什么
人工智能·windows·电脑·知识图谱
ITHAOGE1516 小时前
2026年Win7最终版ISO系统映像下载!(集成补丁、旗舰版、完整无精简、64位/32位可选、Windows 7、简体中文/繁体中文/英语可选)
windows·科技·microsoft·微软·电脑
yuanpan16 小时前
Python + PyAutoGUI 实战:Windows 自动化办公脚本开发入门
windows·python·自动化