C#Windows服务程序开发实例浅析
C#Windows服务程序开发实例浅析http://developer.51cto.com 2009-08-14 14:17 maweiaixx cnblogs 我要评论( 0)
C#Windows服务程序开发实例向你介绍希望对你了解和学习C#Windows服务程序开发有所帮助。
C#Windows服务程序开发实例:编写一个C#Windows服务程序,定时做一些事情
测试环境:Visual Studio 2005 SP1、Windows Server 2003 SP2
C#Windows服务程序开发实例一、新建项目
打开VS2005,新建一个“Windows 服务”项目。
C#Windows服务程序开发实例二、添加Timer
展开“工具箱”,在“组件”标签下找到“Timer”双击,这时就添加了一个Timer组件,修改“Name”属性为“timer1”、“Enabled”为“false”、“Interval”为“60000”。
接下来要做一些修补工作,不知是VS2005的BUG还是我没找着地方,在VS2003下是不存在该问题的:刚从“组件”下添加的“Timer”按 理说应该来自“System.Timers命名空间”,也只有“System.Timers.Timer”才能在Windows服务程序中正常工作,但是 现在这个Timer却是属于“System.Windows.Forms.Timer”的。所以得稍作修改,打开“.Designer.cs”文件,修改 如下:
#region 组件设计器生成的代码
//........以上略
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
//this.timEmail = new System.Windows.Forms.Timer(this.components);原
this.timEmail = new System.Timers.Timer();//改
this.timEmail.Interval = 60000;
this.ServiceName = "Service1";
}
#endregion
//private System.Windows.Forms.Timer timer1;原
private System.Timers.Timer timer1;//改
C#Windows服务程序开发实例四、以下是实现代码
using System;
using System.Collections.Generic;
using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Linq;using System.ServiceProcess;using System.Text;using System.Data.SqlClient;using System.IO;using JustinIO;using SMS;using System.Drawing;using Mobile;namespace SendService{ public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { this.timer1.Enabled = true; } protected override void OnStop() { this.timer1.Enabled = false; } private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { // 要做的事情 }
C#Windows服务程序开发实例五、布署服务
在设计模式下右键-->添加安装程序-->设置serviceProcessInstaller1的Account为LocalSystem
设置serviceInstaller1的StartType为Automatic
编译
在命令模式下执行:%systemroot%\microsoft.net\framework\v2.0.50727\installUtil.exe D:\项目目录\bin\Debug\可执行文件名.exe
在每次需要修改Windows服务时,这就会要求你卸载和重新安装这个服务。不过要注意在卸载这个服务前,最好确保服务管理控制台已经关闭,这会是 一个很好的习惯。如果没有这样操作的话,你可能在卸载和重安装Windows服务时会遇到麻烦。仅卸载服务的话,可以执行相的InstallUtil命令 用于注销服务,不过要在后面加一个/u命令开关。
调试Windows服务
从另外的角度度看,调试Windows服务绝不同于一个普通的应用程序。调试Windows服务要求的步骤更多。服务不能象你对普通应用程序做的那 样,只要简单地在开发环境下执行就可以调试了。服务必须首先被安装和启动,这一点在前面部分我们已经做到了。为了便于跟踪调试代码,一旦服务被启动,你就 要用Visual Studio把运行的进程附加进来(attach)。记住,对你的Windows服务做的任何修改都要对这个服务进行卸载和重安装。
附加正在运行的Windows服务
--------------------编程问答-------------------- up --------------------编程问答-------------------- mark。 --------------------编程问答-------------------- 很简练!
但是有没讨论关于服务程序编写的地方? --------------------编程问答-------------------- 好资料!!!!!!!!!!!!!!1
补充:.NET技术 , C#