C#Windows服务程序开发实例浅析

C#Windows服务程序开发实例:编写一个C#Windows服务程序,定时从数据库中拿出记录发送邮件。

测试环境:Visual Studio 2005 SP1、Windows Server 2003 SP2

C#Windows服务程序开发实例一、新建项目

打开VS2005,新建一个“Windows 服务”项目。

C#Windows服务程序开发实例二、添加Timer

展开“工具箱”,在“组件”标签下找到“Timer”双击,这时就添加了一个Timer组件,修改“Name”属性为“timEmail”、“Enabled”为“false”、“Interval”为“60000”。

接下来要做一些修补工作,不知是VS2005的BUG还是我没找着地方,在VS2003下是不存在该问题的:刚从“组件”下添加的“Timer”按理说应该来自“System.Timers命名空间”,也只有“System.Timers.Timer”才能在Windows服务程序中正常工作,但是现在这个Timer却是属于“System.Windows.Forms.Timer”的。所以得稍作修改,打开“.Designer.cs”文件,修改如下:

 
 
 
  1. #region 组件设计器生成的代码
  2. //........以上略
  3. ///  
  4. /// 设计器支持所需的方法 - 不要
  5. /// 使用代码编辑器修改此方法的内容。
  6. /// 
  7. private void InitializeComponent()
  8. {
  9.     this.components = new System.ComponentModel.Container();
  10.     //this.timEmail = new System.Windows.Forms.Timer(this.components);原
  11.     this.timEmail = new System.Timers.Timer();//改
  12.     this.timEmail.Interval = 60000;
  13.     this.ServiceName = "Service1";
  14. }
  15. #endregion
  16. //private System.Windows.Forms.Timer timEmail;原
  17. private System.Timers.Timer timEmail;//改

C#Windows服务程序开发实例三、添加配置文件

服务每次调用配置文件,获取一些基本参数,这样一些变更就可直接修改配置文件而不必修改代码。新建ServiceConfig.xml存放于项目“Bin\Debug\”下:

 
 
 
  1. ﹤?xml version="1.0" encoding="utf-8" ?﹥ 
  2. ﹤serviceConfig﹥
  3.     ﹤serviceItem 
  4. name="sendEmail" 
  5. enable="true" 
  6. elapsed="60000" 
  7. connectionString="your database connection..." 
  8. smtp="smtp address" 
  9. account="your email account..." 
  10. password="your password..." ﹥
  11.     ﹤/serviceItem﹥
  12. ﹤/serviceConfig﹥

C#Windows服务程序开发实例四、以下是实现代码

 
 
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.ServiceProcess;
  7. using System.Text;
  8. using System.Xml;//操作配置文件
  9. using System.IO;//写日志
  10. using System.Threading;//使用线程
  11. namespace ClientWindowsService
  12. {
  13.     public partial class ClientService : ServiceBase
  14.     {
  15. public ClientService()
  16. {
  17.     InitializeComponent();
  18. }
  19. protected override void OnStart(string[] args)
  20. {
  21.     //服务启动
  22.       this.timEmail.Enabled = true;
  23.     this.tSendEmail();
  24. }
  25. protected override void OnStop()
  26. {
  27.     //服务停止
  28.       this.timEmail.Enabled = false;
  29. }
  30. private void timEmail_Elapsed(object sender,
  31.  System.Timers.ElapsedEventArgs e)
  32. {
  33.     //定时器
  34.       this.tSendEmail();
  35. }
  36. //开启新进程发送邮件
  37.     private void tSendEmail()
  38. {
  39.     Thread t = new Thread(new ThreadStart(sendEmail));
  40.     t.Start();
  41. }
  42. //发送邮件函数
  43.     private void sendEmail()
  44. {
  45.     XmlDocument doc = new XmlDocument();
  46.     //添加System.Windows.Forms引用,获取执行目录
  47.       string configFile = System.Windows.Forms.Application.
  48. StartupPath.ToString() + "\ServiceConfig.xml";
  49.     doc.Load(@configFile);
  50.     XmlElement root = doc.DocumentElement;
  51.     foreach (XmlNode node in root)
  52.     {
  53. //如果配置文件中开启服务
  54. if (node.Attributes["name"].Value == "sendEmail" &&
  55.  node.Attributes["enable"].Value == "true")
  56. {
  57.     try
  58.     {
  59. //读取数据库,发送邮件操作,略
  60.     }
  61.     catch (Exception error)
  62.     {
  63. //写错误日志
  64.     using (StreamWriter sw = new
  65. StreamWriter(System.Windows.Forms.
  66. Application.StartupPath.ToString() +
  67. @"" + DateTime.Now.ToString("yyyy-MM-dd") +
  68. ".txt", true, System.Text.Encoding.UTF8))
  69. {
  70.     sw.WriteLine(DateTime.Now.ToString() + ":");
  71.     sw.WriteLine(error.ToString());
  72.     sw.WriteLine("----------------
  73. -----------------------------");
  74.     sw.Close();
  75. }
  76.     }
  77. }
  78.     }//end foreach
  79. }
  80.     }//end class
  81. }//end namespace

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服务

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

1. 用Visual Studio装载这个项目

2. 点击“调试”菜单

3. 点击“进程”菜单

4. 确保 显示系统进程 被选

5. 在 可用进程 列表中,把进程定位于你的可执行文件名称上点击选中它

6. 点击 附加 按钮

7. 点击 确定

8. 点击 关闭

9. 在timer1_Elapsed方法里设置一个断点,然后等它执行

C#Windows服务程序开发实例六、代码下载

http://files.cnblogs.com/linckle/log.rar

C#Windows服务程序开发实例的基本内容就向你介绍到这里,希望对你学习和了解C#Windows服务程序开发实例有所帮助。

本文题目:C#Windows服务程序开发实例浅析
标题URL:http://www.hantingmc.com/qtweb/news0/339700.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联