前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >用.NET创建Windows服务

用.NET创建Windows服务

作者头像
Java架构师必看
发布于 2021-03-22 04:08:36
发布于 2021-03-22 04:08:36
1.1K00
代码可运行
举报
文章被收录于专栏:Java架构师必看Java架构师必看
运行总次数:0
代码可运行

用.NET创建Windows服务

译者说明:我是通过翻译来学习C#的,文中涉及到的有Visual Studio.NET有关操作,我都根据中文版的VS.NET显示信息来处理的,可以让大家不致有误解。

作者:Mark Strawmyer

我们将研究如何创建一个作为Windows服务的应用程序。内容包含什么是Windows服务,如何创建、安装和调试它们。会用到System.ServiceProcess.ServiceBase命名空间的类。

什么是Windows服务?

Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合。它没有用户界面,并且也不会产生任何可视输出。任何用户消息都会被写进Windows事件日志。计算机启动时,服务会自动开始运行。它们不要用户一定登录才运行,它们能在包括这个系统内的任何用户环境下运行。通过服务控制管理器,Windows服务是可控的,可以终止、暂停及当需要时启动。

Windows 服务,以前的NT服务,都是被作为Windows NT操作系统的一部分引进来的。它们在Windows 9x及Windows Me下没有。你需要使用NT级别的操作系统来运行Windows服务,诸如:Windows NT、Windows 2000 Professional或Windows 2000 Server。举例而言,以Windows服务形式的产品有:Microsoft Exchange、SQL Server,还有别的如设置计算机时钟的Windows Time服务。

创建一个Windows服务

我们即将创建的这个服务除了演示什么也不做。服务被启动时会把一个条目信息登记到一个数据库当中来指明这个服务已经启动了。在服务运行期间,它会在指定的时间间隔内定期创建一个数据库项目记录。服务停止时会创建最后一条数据库记录。这个服务会自动向Windows应用程序日志当中登记下它成功启动或停止时的记录。

Visual Studio .NET能够使创建一个Windows服务变成相当简单的一件事情。启动我们的演示服务程序的说明概述如下。

1. 新建一个项目 2. 从一个可用的项目模板列表当中选择Windows服务 3. 设计器会以设计模式打开 4. 从工具箱的组件表当中拖动一个Timer对象到这个设计表面上 (注意: 要确保是从组件列表而不是从Windows窗体列表当中使用Timer) 5. 设置Timer属性,Enabled属性为False,Interval属性30000毫秒 6. 切换到代码视图页(按F7或在视图菜单当中选择代码),然后为这个服务填加功能

Windows服务的构成

在你类后面所包含的代码里,你会注意到你所创建的Windows服务扩充了System.ServiceProcess.Service类。所有以.NET方式建立的Windows服务必须扩充这个类。它会要求你的服务重载下面的方法,Visual Studio默认时包括了这些方法。

• Dispose – 清除任何受控和不受控资源(managed and unmanaged resources) • OnStart – 控制服务启动 • OnStop – 控制服务停止

数据库表脚本样例

在这个例子中使用的数据库表是使用下面的T-SQL脚本创建的。我选择SQL Server数据库。你可以很容易修改这个例子让它在Access或任何你所选择的别的数据库下运行。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
CREATE TABLE [dbo].[MyServiceLog] (
 [in_LogId] [int] IDENTITY (1, 1) NOT NULL,
 [vc_Status] [nvarchar] (40)
 COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [dt_Created] [datetime] NOT NULL
 ) ON [PRIMARY]

Windows服务样例

下面就是我命名为MyService的Windows服务的所有源代码。大多数源代码是由Visual Studio自动生成的。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
using System;
 using System.Collections;
 using System.ComponentModel;
 using System.Data;
 using System.Data.SqlClient;
 using System.Diagnostics;
 using System.ServiceProcess;
namespace CodeGuru.MyWindowsService
 {
 public class MyService : System.ServiceProcess.ServiceBase
 {
 private System.Timers.Timer timer1;
 /// <remarks>
 /// Required designer variable.
 /// </remarks>
 private System.ComponentModel.Container components = null;
public MyService()
 {
 // This call is required by the Windows.Forms
 // Component Designer.
 InitializeComponent();
 }
// The main entry point for the process
 static void Main()
 {
 System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[]
 { new MyService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
 }
/// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
 this.timer1 = new System.Timers.Timer();
 ((System.ComponentModel.ISupportInitialize)
 (this.timer1)).BeginInit();
 //
 // timer1
 //
 this.timer1.Interval = 30000;
 this.timer1.Elapsed +=
 new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
 //
 // MyService
 //
 this.ServiceName = "My Sample Service";
 ((System.ComponentModel.ISupportInitialize)
 (this.timer1)).EndInit();
}
/// <summary>
 /// Clean up any resources being used.
 /// </summary>
 protected override void Dispose( bool disposing )
 {
 if( disposing )
 {
 if (components != null)
 {
 components.Dispose();
 }
 }
 base.Dispose( disposing );
 }
/// <summary>
 /// Set things in motion so your service can do its work.
 /// </summary>
 protected override void OnStart(string[] args)
 {
 this.timer1.Enabled = true;
 this.LogMessage("Service Started");
 }
/// <summary>
 /// Stop this service.
 /// </summary>
 protected override void OnStop()
 {
 this.timer1.Enabled = false;
 this.LogMessage("Service Stopped");
 }
/*
 * Respond to the Elapsed event of the timer control
 */
 private void timer1_Elapsed(object sender,
 System.Timers.ElapsedEventArgs e)
 {
 this.LogMessage("Service Running");
 }
/*
 * Log specified message to database
 */
 private void LogMessage(string Message)
 {
 SqlConnection connection = null;
 SqlCommand command = null;
 try
 {
 connection = new SqlConnection(
 "Server=localhost;Database=SampleDatabase;Integrated
 Security=false;User Id=sa;Password=;");
 command = new SqlCommand(
 "INSERT INTO MyServiceLog (vc_Status, dt_Created)
 VALUES ('" + Message + "',getdate())", connection);
 connection.Open();
 int numrows = command.ExecuteNonQuery();
 }
 catch( Exception ex )
 {
 System.Diagnostics.Debug.WriteLine(ex.Message);
 }
 finally
 {
 command.Dispose();
 connection.Dispose();
 }
 }
 }
 }

安装Windows服务

Windows服务不同于普通Windows应用程序。不可能简简单单地通过运行一个EXE就启动Windows服务了。安装一个Windows服务应该通过使用.NET Framework提供的InstallUtil.exe来完成,或者通过诸如一个Microsoft Installer (MSI)这样的文件部署项目完成。

添加服务安装程序

创建一个Windows服务,仅用InstallUtil程序去安装这个服务是不够的。你必须还要把一个服务安装程序添加到你的Windows服务当中,这样便于InstallUtil或是任何别的安装程序知道应用你服务的是怎样的配置设置。

1. 将这个服务程序切换到设计视图 2. 右击设计视图选择“添加安装程序” 3. 切换到刚被添加的ProjectInstaller的设计视图 4. 设置serviceInstaller1组件的属性: 1) ServiceName = My Sample Service 2) StartType = Automatic 5. 设置serviceProcessInstaller1组件的属性 1) Account = LocalSystem 6. 生成解决方案

在完成上面的几个步骤之后,会自动由Visual Studio产生下面的源代码,它包含于ProjectInstaller.cs这个源文件内。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
using System;
 using System.Collections;
 using System.ComponentModel;
 using System.Configuration.Install;
namespace CodeGuru.MyWindowsService
 {
 /// <summary>
 /// Summary description for ProjectInstaller.
 /// </summary>
 [RunInstaller(true)]
 public class ProjectInstaller :
 System.Configuration.Install.Installer
 {
 private System.ServiceProcess.ServiceProcessInstaller
 serviceProcessInstaller1;
 private System.ServiceProcess.ServiceInstaller serviceInstaller1;
 /// <summary>
 /// Required designer variable.
 /// </summary>
 private System.ComponentModel.Container components = null;
public ProjectInstaller()
 {
 // This call is required by the Designer.
 InitializeComponent();
// TODO: Add any initialization after the InitComponent call
 }
#region Component Designer generated code
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
 this.serviceProcessInstaller1 = new
 System.ServiceProcess.ServiceProcessInstaller();
 this.serviceInstaller1 = new
 System.ServiceProcess.ServiceInstaller();
 //
 // serviceProcessInstaller1
 //
 this.serviceProcessInstaller1.Account =
 System.ServiceProcess.ServiceAccount.LocalSystem;
 this.serviceProcessInstaller1.Password = null;
 this.serviceProcessInstaller1.Username = null;
 //
 // serviceInstaller1
 //
 this.serviceInstaller1.ServiceName = "My Sample Service";
 this.serviceInstaller1.StartType =
 System.ServiceProcess.ServiceStartMode.Automatic;
 //
 // ProjectInstaller
 //
 this.Installers.AddRange(new
 System.Configuration.Install.Installer[]
 {this.serviceProcessInstaller1, this.serviceInstaller1});
 }
 #endregion
 }
 }

用InstallUtil安装Windows服务

现在这个服务已经生成,你需要把它安装好才能使用。下面操作会指导你安装你的新服务。

1. 打开Visual Studio .NET命令提示 2. 改变路径到你项目所在的bin/Debug文件夹位置(如果你以Release模式编译则在bin/Release文件夹) 3. 执行命令“InstallUtil.exe MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。 4. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台 5. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了 6. 右击你的服务选择启动就可以启动你的服务了

在每次需要修改Windows服务时,这就会要求你卸载和重新安装这个服务。不过要注意在卸载这个服务前,最好确保服务管理控制台已经关闭,这会是一个很好的习惯。如果没有这样操作的话,你可能在卸载和重安装Windows服务时会遇到麻烦。仅卸载服务的话,可以执行相的InstallUtil命令用于注销服务,不过要在后面加一个/u命令开关。

调试Windows服务

从另外的角度度看,调试Windows服务绝不同于一个普通的应用程序。调试Windows服务要求的步骤更多。服务不能象你对普通应用程序做的那样,只要简单地在开发环境下执行就可以调试了。服务必须首先被安装和启动,这一点在前面部分我们已经做到了。为了便于跟踪调试代码,一旦服务被启动,你就要用Visual Studio把运行的进程附加进来(attach)。记住,对你的Windows服务做的任何修改都要对这个服务进行卸载和重安装。

附加正在运行的Windows服务

为了调试程序,有些附加Windows服务的操作说明。这些操作假定你已经安装了这个Windows服务并且它正在运行。

1. 用Visual Studio装载这个项目 2. 点击“调试”菜单 3. 点击“进程”菜单 4. 确保 显示系统进程 被选 5. 在 可用进程 列表中,把进程定位于你的可执行文件名称上点击选中它 6. 点击 附加 按钮 7. 点击 确定 8. 点击 关闭 9. 在timer1_Elapsed方法里设置一个断点,然后等它执行

总结

现在你应该对Windows服务是什么,以及如何创建、安装和调试它们有一个粗略的认识了。Windows服务的额处的功能你可以自行研究。这些功能包括暂停(OnPause)和恢复(OnContinue)的能力。暂停和恢复的能力在默认情况下没有被启用,要通过Windows服务属性来设置。

本文由来源 21aspnet,由 javajgs_com 整理编辑,其版权均为 21aspnet 所有,文章内容系作者个人观点,不代表 Java架构师必看 对观点赞同或支持。如需转载,请注明文章来源。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Windows服务创建及安装
我们将研究如何创建一个作为Windows服务的应用程序。内容包含什么是Windows服务,如何创建、安装和调试它们。会用到System.ServiceProcess.ServiceBase命名空间的类。 什么是Windows服务?    Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合。它没有用户界面,并且也不会产生任何可视输出。任何用户消息都会被写进Windows事件日志。计算机启动时,服务会自动开始运行。它们不要用户一定登录才运行,它们能在包括这个系统内的任何用户环境下运
hbbliyong
2018/03/06
1.5K0
VS 2010一步步开发windows服务(windows service)
 基于0起步来创建一个服务,做到简单的记录时间日志功能,其具体招行方法可自行添加。 1.创建服务 2.删除默认服务文件 3.添加自己的服务文件 4.更改启动项目 5. 引用 using System.
欢醉
2018/01/22
8230
VS 2010一步步开发windows服务(windows service)
在c#中创建Windows服务
Windows服务通常在操作系统OS启动并在后台运行应用程序时启动。Windows服务在自己的会话中执行应用程序。它可以自动启动,也可以手动暂停、停止和重新启动。
程序你好
2018/07/23
4.4K0
使用C#创建Windows服务
CNXY
2017/12/25
1.7K0
使用C#创建Windows服务
使用InstallUtil发布windows服务
   a)ServiceName =”FirstService”;   //设置服务名称
写代码的猿
2019/04/11
1.2K0
使用InstallUtil发布windows服务
使用Visual Studio 2015 Community 开发windows服务
  昨天研究在.NET下开发Windows服务程序,期间遇到一些小问题,这里仅将自己的开发过程和需要注意的地方写下和广大网友分享……
雪飞鸿
2018/09/05
7730
使用Visual Studio 2015 Community 开发windows服务
c#之添加window服务(定时任务)
3.在下图安装程序 serviceInstaller1 上右键,修改serviceName和Description
Vincent-yuan
2019/09/10
2.8K0
c#之添加window服务(定时任务)
C# 创建Windows服务demo
1.新建一个Windows Service,并将项目名称改为“MyWinsService”,程序保存路径自己选一个,如下图所示:
用户7053485
2020/03/19
8740
C# 创建Windows服务demo
创建Windows服务(Windows Services)N种方式总结
最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。 目前我知道的创建创建Windows服务有3种方式: a.利用.net框架类ServiceBase b.利用组件Topshelf c.利用小工具instsrv和srvany
跟着阿笨一起玩NET
2018/09/19
1.2K0
创建Windows服务(Windows Services)N种方式总结
Windows服务的用法和使用场景
Windows服务是可以在系统启动时自动打开的程序,它们在后台运行,不需要用户交互。
软件架构师Michael
2024/11/11
1880
C#创建Windows Service(Windows 服务)基础教程
Windows Service这一块并不复杂,但是注意事项太多了,网上资料也很凌乱,偶尔自己写也会丢三落四的。所以本文也就产生了,本文不会写复杂的东西,完全以基础应用的需求来写,所以不会对Windows Service写很深入。
跟着阿笨一起玩NET
2018/09/18
2.1K0
C#创建Windows Service(Windows 服务)基础教程
C#创建一个Window服务
Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。本文就向大家介绍如何运用Visual C#来一步一步创建一个文件监视的Windows服务程序,然后介绍如何安装、测试和调试该Windows服务程序。
用户1055830
2019/05/25
6530
.Net实现Windows服务安装完成后自动启动的两种方法
考虑到部署方便,我们一般都会将C#写的Windows服务制作成安装包。在服务安装完成以后,第一次还需要手动启动服务,这样非常不方便。 方法一:在安装完成事件里面调用命令行的方式启动服务 此操作之前要先设置下两个控件 设置serviceProcessInstaller1控件的Account属性为“LocalSystem” 设置serviceInstaller1控件的StartType属性为"Automatic" 在服务器上添加安装程序,在private void ProjectInstaller_Afte
hbbliyong
2018/03/06
1.6K0
.Net实现Windows服务安装完成后自动启动的两种方法
Windows服务的快速搭建与调试(C#图解)
目录 一、什么是Windows 服务? 二、创建Windows 服务与安装/卸载批处理。 三、调试Windows 服务。 正文 一、什么是Windows 服务? 答:Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以
磊哥
2018/05/08
2.3K0
Windows服务的快速搭建与调试(C#图解)
WCF 学习总结1 -- 简单实例
从VS2005推出WCF以来,WCF逐步取代了Remoting, WebService成为.NET上分布式程序的主要技术。WCF统一的模型整合了以往的 WebService、Remoting、MSMQ
hbbliyong
2018/03/05
9920
WCF 学习总结1 -- 简单实例
winform scm服务
服务启动 static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } 服务组件 serivice.cs 鼠标右键添加安装程序 serviceProcessInstaller1 的账户设置成localsystem否则安装时提示密码登录 se
sofu456
2020/06/08
9160
C#/.NET基于Topshelf创建Windows服务程序及服务的安装和卸载(极速,简洁)
对于使用Windows操作系统的人来说,Windows Service(Windows服务)应该不会陌生。在Windows操作系统中,我们可以在"运行"窗口中运行service.msc:
Rector
2020/06/19
2K0
WCF系列教程之WCF服务宿主与WCF服务部署
本文参考自http://www.cnblogs.com/wangweimutou/p/4377062.html,纯属读书笔记,加深记忆。 一、简介 任何一个程序的运行都需要依赖一个确定的进程中,WCF也不例外。如果我们需要使用WCF服务,那么我们就必须将服务寄宿与创建它并控制它的上下文和生存期的运行时环境当中,承载服务的环境,称之为宿主。WCF服务可以在支持托管代码的任意Windows进程中运行。WCF提供了统一编程模型,用于生成面向服务的应用程序。此编程模型保持一致且独立于部署服务的运行时环境。 实际上,
郑小超.
2018/01/26
1.5K0
使用windows服务和MSMQ和进行日志管理(解决高并发问题)
然后就可以写我们的代码了,我们的服务需要实时监视MSMQ的队列中有没有记录,如果有,就向数据库中插入
跟着阿笨一起玩NET
2018/09/19
1.6K0
使用windows服务和MSMQ和进行日志管理(解决高并发问题)
Windows 服务 同时启动多个服务
最近需要开发 Windows Service 程序,之前没有接触过,所以把了解到的一些东西记录下来。
独立观察员
2022/12/06
1.6K0
Windows 服务 同时启动多个服务
相关推荐
Windows服务创建及安装
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验