当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用Windows Service的简单教程(创建、安装、卸载、调试)

C#使用Windows Service的简单教程(创建、安装、卸载、调试)

2019年07月18日  | 移动技术网IT编程  | 我要评论

前言:microsoft windows 服务能够创建在它们自己的 windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。本文就向大家介绍如何运用c#来创建、安装、卸载、调试windows service程序。

一、创建windows服务

1)用vs新建windows 服务项目

2)默认生成文件包括program.cs,service1.cs。重命名service1.cs为你的服务名或删除service1.cs文件然后创建自己的服务文件,假设取服务名字为myservice。注意:如果是删除service1.cs文件然后创建自己的服务文件,需要将program.cs文件里的service1修改为myservice。

myservice.cs属性窗口中,相关属性如下:

autolog      是否自动写入系统的日志文件
canhandlepowerevent  服务时候接受电源事件
canpauseandcontinue 服务是否接受暂停或继续运行的请求
canshutdown        服务是否在运行它的计算机关闭时收到通知,以便能够调用 onshutdown 过程
canstop 服务是否接受停止运行的请求
servicename 服务名

注意:canpauseandcontinue和canshutdown的默认值均为false,要想使服务的onpause()、oncontinue()、onshutdown()起作用,需要将canpauseandcontinue和canshutdown属性值设置为true。

3)双击myservice.cs服务文件,在左侧设计模式中,右键点击“添加安装程序”(或者在myservice.cs的属性窗口的下方点击添加“添加安装程序”;如果看不到“添加安装程序”的可点链接,可以右键属性窗口,点击“命令(c)”后就会出来了。注意:是属性窗口而不是文件属性窗口),会自动生成projectinstaller.cs文件以及两个安装组件,如下:

4)单击“serviceprocessinstaller1”,在其属性窗口中设置account帐号方式,建议为localservice(当然也可以account属性改为 localsystem,这样,不论是以哪个用户登录的系统,服务总会启动)。

5)单击“serviceinstaller1”,在其属性窗口设置属性:

  a)description 服务描述,直接显示到windows服务列表中的描述;

  b)displayname 服务显示名称,直接显示到windows服务列表中的名称;

  c)servicename 服务进程名称,安装与卸载服务时的唯一标识。

具体设置如上图所示。

6)创建安装服务批处理文件install.bat,可以创建记事本,然后修改后缀为bat,记事本内容如下:

%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exewindowsservicedemo.exe
net startmyservice
sc config myservicestart= auto
pause

注意:记事本另存为时设置编码为ansi

说明:第二行为启动服务,第三行为设置服务为自动运行,这两行视服务形式自行选择。如果需要查看脚本运行状况,在脚本最后一行加入pause。

7)同理创建卸载服务批处理文件uninstall.bat,内容如下:

%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe /uwindowsservicedemo.exe
pause

8)将install.bat以及uninstall.bat这两个文件添加到bin\debug目录下,此时解决方案的目录结构如下:

9)写服务代码,以向文本文件写入文本记录系统时间为例:

using system;
using system.io;
using system.diagnostics;
using system.serviceprocess;
using system.timers;

namespace windowsservicedemo
{
 public partial class myservice : servicebase
 {
 private timer time = new timer();
 public myservice()
 {
 initializecomponent();
 }

 protected override void onstart(string[] args)
 {
 #if debug
 if (!debugger.isattached)
 debugger.launch();
 debugger.break();
 #endif
 writelog("服务启动,时间:" + datetime.now.tostring("hh:mm:ss") + "\r\n");
 time.elapsed += new elapsedeventhandler(methodevent);
 time.interval = 60 * 1000;//时间间隔为2秒钟
 time.start();
 }

 protected override void onstop()
 {
 #if debug
 if (!debugger.isattached)
 debugger.launch();
 debugger.break();
 #endif
 writelog("服务停止,时间:" + datetime.now.tostring("hh:mm:ss") + "\r\n");
 }

 protected override void onpause()
 {
 #if debug
 if (!debugger.isattached)
 debugger.launch();
 debugger.break();
 #endif
 writelog("服务暂停,时间:" + datetime.now.tostring("hh:mm:ss") + "\r\n");
 base.onpause();
 }

 protected override void oncontinue()
 {
 #if debug
 if (!debugger.isattached)
 debugger.launch();
 debugger.break();
 #endif
 writelog("服务恢复,时间:" + datetime.now.tostring("hh:mm:ss") + "\r\n");
 base.oncontinue();
 }

 protected override void onshutdown()
 {
 writelog("计算机关闭,时间:" + datetime.now.tostring("hh:mm:ss") + "\r\n");
 base.onshutdown();
 }

 private void methodevent(object source, system.timers.elapsedeventargs e)
 {
 time.enabled = false;
 string result = string.empty;
 try
 {
 //.........
 result = "执行成功,时间:" + datetime.now.tostring("hh:mm:ss") + "\r\n";
 }
 catch (exception ex)
 {
 result = "执行失败,原因:" + ex.message + "\r\n";
 }
 finally
 {
 writelog(result);
 time.enabled = true;
 }
 }
 /// <summary>
 /// 日志记录
 /// </summary>
 /// <param name="loginfo"></param>
 private void writelog(string loginfo)
 {
 try
 {
 string logdirectory = appdomain.currentdomain.basedirectory + "\\logs";
 if (!directory.exists(logdirectory))
 {
  directory.createdirectory(logdirectory);
 }
 string filepath = logdirectory + "\\" + datetime.now.tostring("yyyy-mm-dd") + ".txt";
 file.appendalltext(filepath, loginfo);
 }
 catch
 { 

 }
 }
 }
}

注意:代码编写完成后,你无法点击通过启动按钮或按f5来运行或调试服务,会弹出如下图所示的警告:

二、安装windows服务

项目生成成功后,定位到bin\debug目录,以管理员身份运行install.bat安装服务,成功结果如下图:

这时,“我的电脑”右键,选择“管理”,选择“服务和应用程序”下的“服务”,就可以看到服务已安装,如下图:

同时,debug文件夹里有了logs文件夹,logs文件夹里有txt文档,内容如下:

可以看到,每分钟执行一次。

三、调试windows服务

1)通常的处理办法是,在service运行后, 在调试器中选择“附加到进程”,附加自己的服务即可调试。但此法有局限性,例如在service启动时的onstart事件中的代码, 基本上很难调试,往往当attach到我们的service的时候,这部分代码已经执行过了。当然了,你可以让onstart事件之前先睡个20s,趁着服务睡觉的时候赶紧“附加到进程”。system.threading.thread.sleep(1000 * 20);

2)我的做法是,在onstart事件的最开始部分加上“debugger.launch();”的调用, 当service运行到此处时,将会弹出一个选择调试器的对话框,同时暂停在当前位置。这样,我们就做到了在代码中手动的启动调试器。

说明:a)debugger.launch()方法的作用是“启动调试器并将其连接到进程”;

   b)可以手动设置断点,也可以用“debugger.break();”动态设置断点;

   c)为了避免多个调试器实例,可以用“debugger.isattached”属性判断调试器是否已附加到进程,代码片段:

             if (!debugger.isattached) debugger.launch();

   d)为了使调试只在debug模式下生效,release模式下无效,可以用条件编译来处理,代码片段如下:

#if debug
 if (!debugger.isattached)
 debugger.launch();
 debugger.break();
 #endif

   关于条件编译,请查看我的另一篇博客:c#-#define条件编译

   e)在调试服务的其他事件或方法时,同样可以用到。

弹出选择调试器的对话框,以及调试界面如下图所示:

四、卸载windows服务

卸载服务,同样以管理员身份运行uninstall.bat即可,成功结果如下图:

参考链接:

源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网