好文档 - 专业文书写作范文服务资料分享网站

创建Windows服务(Windows Services)N种方式总结

天下 分享 时间: 加入收藏 我要投稿 点赞

最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。 目前我知道的创建创建Windows服务有3种方式: a.利用.net框架类ServiceBase b.利用组件Topshelf

c.利用小工具instsrv和srvany

下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志:

a.利用.net框架类ServiceBase 本方式特点:简单,兼容性好

通过继承.net框架类ServiceBase实现 第1步: 新建一个Windows服务

public partial class Service1 : ServiceBase {

readonly Timer _timer;

private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @\ + \;

public Service1 ( ) {

InitializeComponent ( );

_timer = new Timer ( 5000 ) {

AutoReset = true , Enabled = true };

_timer.Elapsed += delegate ( object sender , ElapsedEventArgs e ) {

this.witre ( string.Format ( \DateTime {0}\ , DateTime.Now ) ); }; }

protected override void OnStart ( string [ ] args ) {

this.witre ( string.Format ( \DateTime {0}\ , DateTime.Now ) ); }

protected override void OnStop ( ) {

this.witre ( string.Format ( \ , DateTime.Now ) + Environment.NewLine ); }

void witre ( string context ) {

StreamWriter sw = File.AppendText ( FileName ); sw.WriteLine ( context ); sw.Flush ( ); sw.Close ( ); } }

第2步: 添加Installer

[RunInstaller ( true )]

public partial class Installer1 : System.Configuration.Install.Installer {

private ServiceInstaller serviceInstaller;

private ServiceProcessInstaller processInstaller;

public Installer1 ( ) {

InitializeComponent ( );

processInstaller = new ServiceProcessInstaller ( ); serviceInstaller = new ServiceInstaller ( );

processInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Automatic;

serviceInstaller.ServiceName = \;

serviceInstaller.Description = \; serviceInstaller.DisplayName = \;

Installers.Add ( serviceInstaller ); Installers.Add ( processInstaller );

} }

第3步:安装,卸载 Cmd命令

installutil WindowsService_test.exe (安装Windows服务) installutil /u WindowsService_test.exe (卸载Windows服务) 代码下载:http://files.cnblogs.com/aierong/WindowsService_test.rar

b.利用组件Topshelf

本方式特点:代码简单,开源组件,Windows服务可运行多个实例

Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com

第1步:引用程序集TopShelf.dll和log4net.dll

第2步:创建一个服务类MyClass,里面包含两个方法Start和Stop,还包含一个定时器Timer,每隔5秒往文本文件中写入字符

public class MyClass {

readonly Timer _timer;

private static readonly string FileName = Directory.GetCurrentDirectory ( ) + @\ + \;

public MyClass ( ) {

_timer = new Timer ( 5000 ) {

AutoReset = true , Enabled = true };

_timer.Elapsed += delegate ( object sender , ElapsedEventArgs e ) {

this.witre ( string.Format ( \DateTime {0}\ , DateTime.Now ) ); };

创建Windows服务(Windows Services)N种方式总结

最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。目前我知道的创建创建Windows服务有3种方式:a.利用.net框架类ServiceBaseb.利用组件Topshelfc.利用小工具instsrv和srvany下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志:
推荐度:
点击下载文档文档为doc格式
5dc8x4kvx08n6j587ker
领取福利

微信扫码领取福利

微信扫码分享