Windows服务样例
下面是一个测试案例,服务名为Service1 黑色部分为自动生成,红色部分为我加进去的代码,绿色为我加入的注释,此案例没有其他意义,只是将记录插入到数据库中。
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Configuration.Install; using SysData.Db;
namespace serverTest { public class Service1 : System.ServiceProcess.ServiceBase { private System.Timers.Timer timer1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null;
public Service1() { // 该调用是 Windows.Forms 组件设计器所必需的。 InitializeComponent();
// TODO: 在 InitComponent 调用后添加任何初始化 }
// 进程的主入口点 static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; // 同一进程中可以运行多个用户服务。若要将 //另一个服务添加到此进程,请更改下行 // 以创建另一个服务对象。例如, // // ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()}; // ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun); }
/// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器 /// 修改此方法的内容。 /// </summary> private void InitializeComponent() { this.timer1 = new System.Timers.Timer(); ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit(); // // timer1 // this.timer1.Enabled = true; this.timer1.Interval = 30000; this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed); // // Service1 // this.ServiceName = "Service1"; ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}
/// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); }
/// <summary> /// 设置具体的操作,以便服务可以执行它的工作。 /// </summary> protected override void OnStart(string[] args) { // TODO: 在此处添加代码以启动服务。 this.timer1.Enabled = true; this.LogMessage("Service Started"); } /// <summary> /// 停止此服务。 /// </summary> protected override void OnStop() { // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 this.timer1.Enabled = false; this.LogMessage("Service Stopped"); }
private void LogMessage(string xMsg) { try { //这里向数据库中插入一条信息为 xMsg的记录,下边是我调用事先写好的Db类添加记录的方法,您也可以使用其他办法来写入数据库。 //Db.QuerySQL("Insert into SysMsg (SysMsg) values ('"+xMsg+"')"); } catch { //不做任何操作 } }
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { LogMessage("检查服务运行!"); } } }
|
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构