创建Windows服务(Windows Services)N种方式总结
最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。
目前我知道的创建创建Windows服务有3种方式:
a.利用.net框架类ServiceBase
b.利用组件Topshelf。更多文章
http://wialoigie.blog.51cto.com 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 ) + @"\" + "test.txt";
public Service1 ( )
{
InitializeComponent ( );
_timer = new Timer ( 5000 )
{
AutoReset = true ,
Enabled = true
};
_timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
{
this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
};
}
protected override void OnStart ( string [ ] args )
{
this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
}
protected override void OnStop ( )
{
this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
}
void witre ( string context )
{
StreamWriter sw = File.AppendText ( FileName );
sw.WriteLine ( context );
sw.Flush ( );
sw.Close ( );
}
}
健康知识
阅读(992) | 评论(0) | 转发(0) |