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服务程序?
相关推荐
淡海水8 小时前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
吴可可12310 小时前
C#调用摄像头拍照的三种API方案
c#
Msir_Modern15 小时前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
云和数据.ChenGuang16 小时前
python sorted函数详细剖析
开发语言·人工智能·windows·python·1024程序员节
星之擎17 小时前
Task 很优雅的取消方式是什么?C# 里面。
开发语言·c#
小熊吃保安18 小时前
Windows也能用 Apple Watch 解锁
windows·rust·开源
czhc114007566318 小时前
一周概念复盘:预热、漂移与门禁
c#
fengye20716119 小时前
Windows 环境下硬核编译 CPython 避坑指南
windows
云中飞鸿19 小时前
.Net和C#有什么关系?(从C++视角观察)
开发语言·c#·.net
成成爱质评21 小时前
Windows 任务计划程序 + 唤醒定时器:让电脑按时开机干活
windows·单片机·电脑