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服务程序?
相关推荐
ι:3 小时前
NUC12 Pro 安装 Ubuntu 24.04 LTS 详细教程
linux·windows·ubuntu·nuc
YCOSA20253 小时前
微软宣布将于10月7日举行Windows与Surface发布会,聚焦“Windows、NVIDIA RTX Spark、Surface,以及更广泛PC生态”
windows
Source.Liu4 小时前
【A11】 labelprinter(Tauri 版)新建步骤
windows·rust
Punchline2785 小时前
解决 Windows 环境变量 Path 设置时提示“字符太长”的完整指南
windows·环境变量·path
chushiyunen5 小时前
claude code笔记(二)、claude桌面端(内网不好用)
windows
d_benhua6 小时前
以太网测试步骤
windows
专注仿真6 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类
冯一川6 小时前
DeepSeek在Windows系统上部署
windows·python
解道Jdon8 小时前
JDK 27发布:紧凑对象头、G1默认、量子安全TLS
ide·windows·git·svn·eclipse·github·visual studio
我是苏苏8 小时前
Agent 开发实战 :C#实现语义检索!向量数据库Qdrant的下载安装及调试步骤
c#·ai编程