一、如何用VS创建Windows服务
1、新建C# Windows服务:windows service工程
2、新建windows service工程后,系统自动生成一个Service1.cs文件,默认是其设计视图。选择查看其代码,默认有构造函数、OnStart、OnStop三个函数
3、新建了C# Windows服务之后,还要设置该服务运行的周期,左侧的ToolBox中有两个timmer,一个在组件下,一个在windows form下,可惜这两个都不能用,我们要手工新建一个timmer,并设置其属性和事件。
Service1.cs代码:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
System.Timers.Timer t = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为10000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(TimeElapse);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
}
public void TimeElapse(object source, System.Timers.ElapsedEventArgs e)
{
//EventLog log = new EventLog();
//log.Source = "我的应用程序";

本文介绍了如何使用C#在Visual Studio中创建Windows服务,详细讲解了服务的生命周期函数,以及如何手动创建Timer。同时阐述了服务安装、卸载的bat脚本和net、sc命令。此外,还探讨了Local System、Network Service和Local Service三种账户的区别及其在服务运行中的权限差异。
最低0.47元/天 解锁文章
1084

被折叠的 条评论
为什么被折叠?



